Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 扣丁音樂(五)——service實現歌曲播放功能

扣丁音樂(五)——service實現歌曲播放功能

編輯:關於Android編程

一丶演示

\

 

丶創建MusicService服務

這裡貼出了後面涉及到的部分代碼

 

/**
 * 實現功能:
 * 1、點擊列表上的某首歌播放
 * 2、點擊播放按鈕,從暫停轉為播放狀態
 * 3、點擊暫停按鈕,從播放狀態轉為暫停狀態
 * 4、上一首
 * 5、下一首
 * 6、播放進度顯示
 * 7、播放模式
 */
public class  MusicPlayService extends Service implements MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener{

    private MediaPlayer mediaPlayer;
    private ArrayList mp3Infos;
    private int currentPosition;//列表當前位置
    private MusicUpdateListener musicUpdateListener;//設置屬性
    private boolean isPause = false;

    //順序播放、單曲循環、隨機播放
    public static final int ORDER_PLAY = 1;
    public static final int RANDOM_PLAY = 2;
    public static final int SINGLE_PLAY = 3;
    public int play_mode = ORDER_PLAY;


    //用於設置或者獲得播放模式
    public int getPlay_mode() {
        return play_mode;
    }

    public void setPlay_mode(int play_mode) {
        this.play_mode = play_mode;
    }


    //在fragment或者activity中輕松獲得狀態
    public boolean isPause(){
        return isPause;
    }

    //開啟線程池
    private ExecutorService es = Executors.newSingleThreadExecutor();

    Runnable updateStatusRunnable = new Runnable() {
        @Override
        public void run() {
            while (true){
                if(musicUpdateListener!=null){
                    musicUpdateListener.onPublish(getCurrentProgress());
                }
            }
        }
    };

    public MusicPlayService() {

    }

    Random random = new Random();
    //用於監聽當前歌曲播放完後,下一首該如何播放
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        switch (play_mode){
            case ORDER_PLAY:
                next();
                break;
            case RANDOM_PLAY:
                play(random.nextInt(mp3Infos.size()));
                break;
            case SINGLE_PLAY:
                play(currentPosition);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        mediaPlayer.reset();
        return false;
    }

    class PlayBinder extends Binder{
        public MusicPlayService getMusicPlayService(){
            return MusicPlayService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        mp3Infos = MediaUtils.getMp3Infos(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
        //在進入每一個綁定service時,就監聽進度改變事件,而狀態改變監聽則是在啟動播放的時候
        es.execute(updateStatusRunnable);
    }

    //啟動線程就得銷毀
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(es!=null && es.isTerminated()){
            es.shutdown();
            es = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    //點擊列表上的某首歌播放
    public void play(int position){
        if(position>=0 && position= mp3Infos.size()-1){
            currentPosition = 0;
        }else{
            currentPosition++;
        }
        play(currentPosition);
    }

    //上一首
    public void previous(){
        if(currentPosition<=0){
            currentPosition = mp3Infos.size()-1;
        }else{
            currentPosition--;
        }
        play(currentPosition);
    }

    //更新狀態的接口
    public interface MusicUpdateListener{
        public void onPublish(int progress);
        public void onChange(int position);
    }

    public void setMusicUpdateListener(MusicUpdateListener musicUpdateListener) {
        this.musicUpdateListener = musicUpdateListener;
    }

    //在音樂播放中,獲得播放的位置信息
    public int getDuration(){
        return mediaPlayer.getDuration();
    }

    //到目前為止,我都不知道這是干什麼用的
    public void seekTo(int msec){
        mediaPlayer.seekTo(msec);
    }

    //返回當前的位置
    public int getCurrentPosition(){
        return currentPosition;
    }

    //獲得當前位置
    public int getCurrentProgress(){
        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            return mediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    //反饋狀態
    public boolean isPlaying(){
        if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
            return mediaPlayer.isPlaying();
        }
        return false;
    }


}
基類BaseActivity(實現Demo中所有服務的綁定和解綁)

 

 

/**
 * 自定義基礎activity,用來讓其他activity繼承,作為工具activity,用於綁定服務
 */
public abstract class BaseActivity extends FragmentActivity {

    protected MusicPlayService musicPlayService;
    private boolean isBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MusicPlayService.PlayBinder playBinder = (MusicPlayService.PlayBinder)iBinder;
            musicPlayService = playBinder.getMusicPlayService();
            musicPlayService.setMusicUpdateListener(musicUpdateListener);
            //綁定成功後調用監聽onChange方法
            musicUpdateListener.onChange(musicPlayService.getCurrentPosition());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicPlayService = null;
            isBound = false;
        }
    };

    private MusicPlayService.MusicUpdateListener musicUpdateListener = new MusicPlayService.MusicUpdateListener(){
        @Override
        public void onPublish(int progress) {
            publish(progress);
        }

        @Override
        public void onChange(int position) {
            change(position);
        }
    };

    public abstract void publish(int progress);
    public abstract void change(int position);

    //綁定服務
    public void bindMusicPlayService(){
        if(!isBound){
            Intent intent = new Intent(this,MusicPlayService.class);
            bindService(intent,conn,BIND_AUTO_CREATE);
            isBound = true;
        }

    }

    //解除綁定服務
    public void unbindMusicPlayService(){
        if(isBound){
            unbindService(conn);
            isBound = false;
        }

    }
}
歡迎頁面中啟動服務(啟動頁面出代碼已貼出)

 

LocalSongsActivity實現監聽,點擊不同音樂播放不同歌曲

 

public class LocalSongsActivity extends BaseActivity implements View.OnClickListener,AdapterView.OnItemClickListener{

    private ListView lv_local_songs_list;
    private ArrayList mp3Infos;
    private LocalSongsListAdapter localSongsListAdapter;
    private ImageView iv_backtrack,iv_album,iv_previous,iv_play,iv_next;
    private TextView tv_song_name1,tv_song_artist1;
    private RelativeLayout rl_music_play_control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_local_songs);
        lv_local_songs_list = (ListView)findViewById(R.id.lv_local_songs_list);
        iv_backtrack = (ImageView)findViewById(R.id.iv_backtrack);
        iv_album = (ImageView) findViewById(R.id.iv_album);
        iv_play = (ImageView)findViewById(R.id.iv_play);
        iv_next = (ImageView)findViewById(R.id.iv_next);
        iv_previous = (ImageView)findViewById(R.id.iv_previous);
        tv_song_name1 = (TextView)findViewById(R.id.tv_song_name1);
        tv_song_artist1 = (TextView)findViewById(R.id.tv_song_artist1);
        rl_music_play_control = (RelativeLayout)findViewById(R.id.rl_music_play_control);
        rl_music_play_control.setOnClickListener(this);
        iv_play.setOnClickListener(this);
        iv_backtrack.setOnClickListener(this);
        iv_next.setOnClickListener(this);
        iv_previous.setOnClickListener(this);
        lv_local_songs_list.setOnItemClickListener(this);
        initDate();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //綁定播放服務
        bindMusicPlayService();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unbindMusicPlayService();
    }

    /**
     * 初始化本地音樂列表
     */
    private void initDate() {
        mp3Infos = MediaUtils.getMp3Infos(this);
        System.out.println(mp3Infos.size());
        localSongsListAdapter = new LocalSongsListAdapter(this,mp3Infos);
        localSongsListAdapter.notifyDataSetChanged();
        lv_local_songs_list.setAdapter(localSongsListAdapter);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_backtrack:
                finish();
                break;
            case R.id.iv_play:
                if(this.musicPlayService.isPlaying()){
                    this.musicPlayService.pause();
                    iv_play.setImageResource(R.drawable.play);
                }else{
                    if(this.musicPlayService.isPause()){
                        this.musicPlayService.start();
                        iv_play.setImageResource(R.drawable.pause);
                    }else {
                        this.musicPlayService.play(0);
                        iv_play.setImageResource(R.drawable.pause);
                    }
                }

                break;
            case R.id.iv_next:
                this.musicPlayService.next();
                iv_play.setImageResource(R.drawable.pause);
                break;
            case R.id.iv_previous:
                this.musicPlayService.previous();
                iv_play.setImageResource(R.drawable.pause);
                break;
            case R.id.rl_music_play_control:
                Intent intent = new Intent(this,PlayUIActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
                break;
        }
    }
    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long id) {
        musicPlayService.play(position);
        iv_play.setImageResource(R.drawable.pause);
    }
    @Override
    public void publish(int progress) {

    }
    @Override
    public void change(int position) {
        //切換狀態播放位置
        changeUIStatus(position);
    }
    //回調播放狀態下的UI設置
    public void changeUIStatus(int position){
        if(position>=0 && positionpause);
            }else {
                iv_play.setImageResource(R.drawable.play);
            }
            //Bitmap albumBitmap =  MediaUtils.getArtwork(this, mp3Info.getTitle(),mp3Info.getId(), mp3Info.getAlbumId(),true);
            Bitmap albumBitmap =  MediaUtils.getArtwork(this,mp3Info.getId(), mp3Info.getAlbumId(),true,false);
            if(albumBitmap==null){
                iv_album.setImageResource(R.drawable.music_play);
            }else{
                iv_album.setImageBitmap(albumBitmap);
            }
        }
    }
}
到這裡,LocalSongsActivity此處的音樂就能播放了,切實現上一曲,下一曲,暫停等功能

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved