Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android練習項目 Mp3播放器實現(二)

Android練習項目 Mp3播放器實現(二)

編輯:關於android開發

Android練習項目 Mp3播放器實現(二)


在經過幾天的折騰之後,迎來了Mp3播放器的第二篇博客,這篇文章主要將如何實現播放器的播放,下一首,上一首,順序播放,循環播放,隨機播放,單曲循環等操作。
其實操作的過程中主要是通過參數的傳遞來實現功能的。
在activity裡面互相傳參有很多中方法,但對於activity和service進行交互有些方法並不適合,通過對Broadcast和BroadcastReceiver等操作,來控制播放的實現。
我們先設定好廣播,然後通過發送信號來進行傳遞數據。
主要在activity裡面動態注冊廣播,通過傳遞播放的順序選擇,Mp3的url,Mp3播放的位置到service裡面,service裡面接受傳來的廣播,獲得參數,在進行對應的操作。
還有一個要解決的問題就是,如何通過service將播放的時間和歌曲信息反饋到activity裡面,然後更新標題,時間,所以就是參數在service和activity之間進行傳遞,在程序中通過handle來處理程序的更新數據,通過handle來和activity交互,但由於沒有開啟線程,所以十分耗時的操作可能不適合,在下一個版本可能需要著手解決這個問題。
所以對於廣播的處理就顯得比較重要了。

先將作出的效果粘貼出來,目前還沒有歌詞等處理。
單曲循環
暫停
列表循環
列表顯示

對於裡面流程的處理十分重要,需要不斷的調試,這是最為花費功夫的。
activity_main.xml布局文件





主要功能通過展示listview來顯示內容。
自定義子部局:
listmusic.xml




    

    

    

    

MainActivity.java
主要獲取mp3文件,對於裡面出現的Mp3infos這個類,參考我上篇文章,這篇文章沒有修改。

package com.flashmusic;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.flashmusic.tool.Mp3Info;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

        //Music的listview控件
        private ListView MusicList;

        // 存儲數據的數組列表
        ArrayList> MusiclistData = new ArrayList>();

        // 適配器
        private SimpleAdapter MusicListAdapter;

        //存放mp3信息
        static  List mp3Infos;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                MusicList = (ListView) findViewById(R.id.listviewmusic);

                mp3Infos = getMp3Infos();
                GetData(mp3Infos);

                MusicListAdapter = new SimpleAdapter(
                        this,
                        MusiclistData,
                        R.layout.listmusic,
                        new String[]{"ID", "Title", "Artist", "Icon"},
                        new int[]{R.id.MusicID, R.id.Musictitle, R.id.MusicArtist, R.id.MusicIcon}
                );
                //賦予數據
                MusicList.setAdapter(MusicListAdapter);

                MusicList.setOnItemClickListener(MusiclistListen);
        }

        AdapterView.OnItemClickListener MusiclistListen = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView adapterView, View view, int i, long l) {
//                         //Toast.makeText(MainActivity.this, String.valueOf(l), Toast.LENGTH_SHORT).show();
//
//                        //判斷當前服務是否已經開啟
//                        if(isServiceRunning(getBaseContext(),"com.flashmusic.MusicService")){
//                                stopService(new Intent(MainActivity.this, MusicService.class));
//                        }
//                        Intent intent   = new Intent();
//                        intent.putExtra("url", mp3Infos.get(i).getUrl());
//                        intent.putExtra("position",String.valueOf(i));
//                        intent.setClass(MainActivity.this, MusicService.class);
//                        //啟動服務
//                        startService(intent);

                        Intent musicintent      = new Intent(MainActivity.this, MusicActivity.class);
                        //當前播放的位置
                        musicintent.putExtra("position", String.valueOf(i));
                        MusicActivity.mp3Infos = mp3Infos;
                   //     MusicActivity.musicserviceintent = intent;
                        //啟動音樂播放界面
                        startActivity(musicintent);
                }
        };

        //判斷服務是否存在
        public static boolean isServiceRunning(Context mContext,String className) {
                boolean isRunning = false;
                ActivityManager activityManager = (ActivityManager)
                        mContext.getSystemService(Context.ACTIVITY_SERVICE);
                List serviceList= activityManager.getRunningServices(50);
                if (!(serviceList.size()>0)) {
                        return false;
                }
                for (int i=0; i mp3Infos) {
                for (int i = 0; i < mp3Infos.size(); i++) {
                        HashMap map = new HashMap();
                        map.put("ID",mp3Infos.get(i).getID());
                        map.put("Title", mp3Infos.get(i).getTitle());
                        map.put("Artist", mp3Infos.get(i).getArtist());
                        map.put("Icon", R.drawable.musicicon);
                        MusiclistData.add(map);
                }
        }

        public List getMp3Infos() {
                Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                        MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
                int ID = 0;
                List mp3Infos = new ArrayList();
                for (int i = 0; i < cursor.getCount(); i++) {
                        Mp3Info mp3Info = new Mp3Info();
                        cursor.moveToNext();
                        long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));   //音樂id,音樂ID不是播放的順序
                        String title = cursor.getString((cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));//音樂標題
                        String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));//藝術家
                        long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//時長
                        long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));  //文件大小
                        String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));              //文件路徑
                        int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否為音樂
                        if (isMusic != 0) {
                                //只把音樂添加到集合當中
                                ID++;
                                mp3Info.setID(ID);
                                mp3Info.setTitle(title);
                                mp3Info.setArtist(artist);
                                mp3Info.setDuration(duration);
                                mp3Info.setSize(size);
                                mp3Info.setUrl(url);
                                mp3Infos.add(mp3Info);
                        }
                }
                return mp3Infos;
        }


        @Override
        public void onItemClick(AdapterView adapterView, View view, int i, long l) {
        }
}

musicplay.xml,播放界面的布局





    

    

    

        

        

        

        

        
    

    

        

        

        

    

接下來就是MusicActivity.java
這裡面有個東西我覺得非常好,就是用了static變量,來共享mp3infos文件信息,通過MainActivity函數來賦值進來,相當於不再需要另一塊內存來存儲數據了,service也是這樣實現的,這樣每次我們只需要將位置position傳進去就能夠解決問題了。

package com.flashmusic;

import com.flashmusic.tool.PlayerMSG;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ThemedSpinnerAdapter;
import android.widget.Toast;

import com.flashmusic.tool.Mp3Info;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;


public class MusicActivity extends Activity implements View.OnClickListener {

    //mp3需要播放的數據
    static List mp3Infos;
    static Intent musicserviceintent;

    //播放按鈕
    private ImageView MusicPlay;
    //下一首
    private ImageView MusicNext;
    //上一首
    private ImageView MusicPrevious;
    //播放方式選擇
    private ImageView MusicMOde;
    //播放菜單
    private ImageView MusicMenu;
    //顯示總時間
    private TextView MusicTime;
    //顯示當前時間
    private TextView MusicCurrentTime;
    //顯示歌曲名
    private TextView MusicTitle;
    //顯示歌曲藝術家
    private TextView MusicArtist;
    //進度條
    SeekBar seekBar;
    //廣播
    MusicPlayerReceiver musicPlayerReceiver;


    private final int isorderplay = 0;//順序播放
    private final int islistloop = 1;//表示列表循環
    private final int isrepeatone = 2;//單曲循環
    private final int israndomplay = 3;//隨機

    public static final String UPDATE_ACTION = "com.flashmusic.action.UPDATE_ACTION";  //更新動作
    public static final String CTL_ACTION = "com.flashmusic.action.CTL_ACTION";        //控制動作
    public static final String MUSIC_CURRENT = "com.flashmusic.action.MUSIC_CURRENT";  //音樂當前時間改變動作
    public static final String MUSIC_DURATION = "com.flashmusic.action.MUSIC_DURATION";//音樂播放長度改變動作
    public static final String MUSIC_PLAYING = "com.flashmusic.action.MUSIC_PLAYING";  //音樂正在播放動作
    public static final String REPEAT_ACTION = "com.flashmusic.action.REPEAT_ACTION";  //音樂重復播放動作
    public static final String SHUFFLE_ACTION = "com.flashmusic.action.RANDOM_ACTION";//音樂隨機播放動作
    public static final String PLAY_STATUE = "com.flashmusic.action.PLAY_STATUE";      //更新播放狀態

    //是否綁定了對應的service
    Boolean mBound = false;
    //播放方式表識0表示順序播放,1表示列表循環,2表示單曲循環,3表示隨機,初始為順序播放
    int playmodeflag = 0;
    //歌曲播放的位置,就能夠獲取位置
    int position;
    int currentTime;
    int duration;//總時間

    //記錄鼠標點擊了幾次,播放和暫停狀態
    boolean playorpauseflag = false;
    //播放服務
    MusicService mService;
    // 正在播放
    private boolean isPlaying;
    // 暫停
    private boolean isPause;

    //多線程,後台更新UI
    Thread myThread;

    //控制後台線程退出
    boolean playStatus = true;


    //轉換毫秒數為時間模式,一般都是分鐘數,音樂文件
    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.musicplay);

        //初始化控件
        InitView();

        //獲得傳過來的值
        Intent intent = getIntent();
        position = Integer.parseInt(intent.getStringExtra("position"));

        MusicArtist.setText(mp3Infos.get(position).getArtist());
        MusicTitle.setText(mp3Infos.get(position).getTitle());

        //注冊廣播
        musicPlayerReceiver = new MusicPlayerReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_ACTION);
        filter.addAction(MUSIC_CURRENT);
        filter.addAction(MUSIC_DURATION);
        filter.addAction(PLAY_STATUE);

        registerReceiver(musicPlayerReceiver, filter);


        //設置響應事件
        MusicNext.setOnClickListener(this);
        MusicPrevious.setOnClickListener(this);
        MusicMenu.setOnClickListener(this);
        MusicMOde.setOnClickListener(this);
        MusicPlay.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
        PlayMusic();
    }

    //初始化控件
    void InitView() {
        MusicPlay = (ImageView) findViewById(R.id.musicplay);
        MusicNext = (ImageView) findViewById(R.id.musicnext);
        MusicPrevious = (ImageView) findViewById(R.id.musicprevious);
        MusicMenu = (ImageView) findViewById(R.id.musicplaymenu);
        MusicMOde = (ImageView) findViewById(R.id.musicplaymode);
        MusicTime = (TextView) findViewById(R.id.playtime);
        MusicCurrentTime = (TextView) findViewById(R.id.playcurrenttime);
        MusicTitle = (TextView) findViewById(R.id.musictitle);
        MusicArtist = (TextView) findViewById(R.id.musicartist);
        seekBar = (SeekBar) findViewById(R.id.MusicProgress);

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.musicplay:
                if (isPlaying) {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicpause, null));
                    intent.setClass(MusicActivity.this, MusicService.class);
                    intent.putExtra("MSG", PlayerMSG.MSG.PAUSE_MSG);
                    startService(intent);
                    isPlaying = false;

                } else {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay, null));
                    intent.setClass(MusicActivity.this, MusicService.class);
                    intent.putExtra("MSG", PlayerMSG.MSG.CONTINUE_MSG);
                    startService(intent);
                    isPlaying = true;
                }
                break;
            case R.id.musicplaymode:
                setPlayMOde();
                break;
            case R.id.musicnext:
                PlayNextMusic();
                break;
            case R.id.musicprevious:
                PlayPreviousMusic();
                break;
            case R.id.musicplaymenu:
                break;
            default:
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    void setPlayMOde() {
        playmodeflag++;
        Intent intent = new Intent(CTL_ACTION);
        intent.putExtra("control", playmodeflag);
        sendBroadcast(intent);
        switch (playmodeflag) {
            case isorderplay:
                MusicMOde.setImageDrawable(getResources().getDrawable(R.drawable.orderplay, null));
                break;
            case islistloop:
                MusicMOde.setImageDrawable(getResources().getDrawable(R.drawable.repeatplay, null));
                break;
            case isrepeatone:
                MusicMOde.setImageDrawable(getResources().getDrawable(R.drawable.repeatoneplay, null));
                break;
            case israndomplay:
                MusicMOde.setImageDrawable(getResources().getDrawable(R.drawable.randomplay, null));
                playmodeflag = -1;
                break;
            default:
                break;
        }

    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        //停止拖動事件
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            //手動調節進度
            // TODO Auto-generated method stub
            //seekbar的拖動位置
            int progress = seekBar.getProgress();

            ChangeProgress(progress);
            //調用service調節播放進度
            //      mService.setProgress(max, dest);
        }

        //數值改變事件
        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
            // TODO Auto-generated method stub
        }

        //開始拖動事件
        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
        }
    };

    public void ChangeProgress(int progress) {
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Infos.get(position).getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.PROGRESS_CHANGE);
        intent.putExtra("progress", progress);
        startService(intent);
    }

    //播放音樂
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayMusic() {
        isPlaying = true;

        MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay, null));
        // 開始播放的時候為順序播放
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Infos.get(position).getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.PLAY_MSG);
        MusicService.mp3Infos = mp3Infos;
        startService(intent);
    }

    //播放上一首音樂
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayPreviousMusic() {
        position = position - 1;
        //   MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicpause,null));

        if (position < 0) {
            position = mp3Infos.size() - 1;
        }
        Mp3Info mp3Info = mp3Infos.get(position);
        MusicTitle.setText(mp3Info.getTitle());
        MusicArtist.setText(mp3Info.getArtist());
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Info.getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.PRIVIOUS_MSG);
        startService(intent);
        isPlaying = true;

        MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay, null));
    }

    //播放下一首音樂
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayNextMusic() {
        //判斷是否是隨機播放,因為隨機播放設置後,playmodeflag變為-1了
        if (playmodeflag == -1) {
            Random random = new Random();
            position = random.nextInt(mp3Infos.size());
        } else
            position = position + 1;
        if (position >= mp3Infos.size())
            position = 0;

        Mp3Info mp3Info = mp3Infos.get(position);
        MusicTitle.setText(mp3Info.getTitle());
        MusicArtist.setText(mp3Info.getArtist());
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Info.getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.NEXT_MSG);
        startService(intent);
        MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay, null));
        isPlaying = true;

    }


    public class MusicPlayerReceiver extends BroadcastReceiver {
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //當前時間更新
            if (action.equals(MUSIC_CURRENT)) {
                currentTime = intent.getIntExtra("currentTime", -1);
                seekBar.setProgress(currentTime);
                MusicCurrentTime.setText(formatDuring(currentTime));


            } else if (action.equals(MUSIC_DURATION)) {
                //總時間更新
                duration = intent.getIntExtra("duration", -1);
                seekBar.setMax(duration);
                MusicTime.setText(formatDuring(duration));

            } else if (action.equals(UPDATE_ACTION)) {
                position = intent.getIntExtra("position", -1);
                String url = mp3Infos.get(position).getUrl();

                MusicTitle.setText(mp3Infos.get(position).getTitle());
                MusicArtist.setText(mp3Infos.get(position).getArtist());
                MusicTime.setText(formatDuring(mp3Infos.get(position).getDuration()));

            } else if (action.equals(PLAY_STATUE)) {
                boolean playstatue = intent.getBooleanExtra("playstatue", true);
                if (playstatue) {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay, null));
                    isPlaying = true;
                } else {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicpause, null));
                    isPlaying = false;
                }
            }

        }
    }

    public void onDestroy() {
        //銷毀activity時,要記得銷毀線程
        playStatus = false;
        super.onDestroy();
    }
}

這裡面有許多細節,處理的過程就是不斷調試。

最為重要的就是寫service了,這個裡面主要涉及到MP3的播放,暫停,切換,上一首,進行操作的主要是接受MusicActivity裡面傳過來的廣播,然後進行判斷,然後處理對應的函數。說的就是這麼簡單,但處理起來,並不是很好解決。
MusicService.java

package com.flashmusic;

import com.flashmusic.tool.PlayerMSG;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


import com.flashmusic.tool.Mp3Info;

import java.util.ArrayList;
import java.util.List;

public class MusicService extends Service {

    // mp3的絕對路徑
    private String path;
    //當前播放位置
    private int position;
    //當前播放進度
    private int currentTime;

    private int msg;                //播放信息

    private boolean isPause;

    static List mp3Infos;    //存放Mp3Info對象的集合

    private int duration;            //播放長度

    int palyflag = 0;


    //服務要發送的一些Action
    public static final String UPDATE_ACTION = "com.flashmusic.action.UPDATE_ACTION";  //更新音樂播放曲目
    public static final String CTL_ACTION = "com.flashmusic.action.CTL_ACTION";        //控制播放模式
    public static final String MUSIC_CURRENT = "com.flashmusic.action.MUSIC_CURRENT";  //當前音樂播放時間更新
    public static final String MUSIC_DURATION = "com.flashmusic.action.MUSIC_DURATION";//播放音樂長度更新
    public static final String PLAY_STATUE = "com.flashmusic.action.PLAY_STATUE";      //更新播放狀態

    //播放音樂的媒體類
    MediaPlayer mediaPlayer;
    //廣播接收器,接收來自MusicActivity的廣播
    private MusicReceiver musicReceiver;


    IBinder musicBinder = new MyBinder();

    //handler用來接收消息,來發送廣播更新播放時間
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mediaPlayer != null) {
                        currentTime = mediaPlayer.getCurrentPosition();
                        Intent intent = new Intent();
                        intent.setAction(MUSIC_CURRENT);
                        intent.putExtra("currentTime", currentTime);
                        sendBroadcast(intent); // 給PlayerActivity發送廣播
                        mHandler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    class MyBinder extends Binder {
        public Service getService() {
            return MusicService.this;
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();

        mediaPlayer = new MediaPlayer();

        /**
         * 設置音樂播放完成時的監聽器
         */
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                Intent intent = new Intent(PLAY_STATUE);
                // 發送播放完畢的信號,更新播放狀態
                intent.putExtra("playstatue", false);
                sendBroadcast(intent);


                //       Toast.makeText(getApplicationContext(),"服務完成了",Toast.LENGTH_SHORT).show();
                if (palyflag == 2) {
                    Intent loopintent = new Intent(PLAY_STATUE);
                    // 發送播放完畢的信號,更新播放狀態
                    intent.putExtra("playstatue", true);
                    sendBroadcast(loopintent);
                    // 單曲循環
                    mediaPlayer.start();

                } else if (palyflag == 1) {
                    // 列表循環
                    position++;
                    if (position > mp3Infos.size() - 1) {
                        //變為第一首的位置繼續播放
                        position = 0;
                    }
                    Intent sendIntent = new Intent(UPDATE_ACTION);
                    sendIntent.putExtra("position", position);
                    // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                    path = mp3Infos.get(position).getUrl();
                    play(0);
                } else if (palyflag == 0) { // 順序播放
                    position++;    //下一首位置
                    if (position <= mp3Infos.size() - 1) {
                        Intent sendIntent = new Intent(UPDATE_ACTION);
                        sendIntent.putExtra("position", position);
                        // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                        path = mp3Infos.get(position).getUrl();
                        play(0);
                    } else {
                        mediaPlayer.seekTo(0);
                        position = 0;
                        Intent sendIntent = new Intent(UPDATE_ACTION);
                        sendIntent.putExtra("position", position);
                        // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                    }
                } else if (palyflag == 3) {    //隨機播放
                    position = getRandomIndex(mp3Infos.size() - 1);
                    Intent sendIntent = new Intent(UPDATE_ACTION);
                    sendIntent.putExtra("position", position);
                    // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                    path = mp3Infos.get(position).getUrl();
                    play(0);
                }
            }
        });

        musicReceiver = new MusicReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CTL_ACTION);
        //     filter.addAction(SHOW_LRC);
        registerReceiver(musicReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        path = intent.getStringExtra("url");        //歌曲路徑
        position = intent.getIntExtra("position", -1);    //當前播放歌曲的在mp3Infos的位置
        msg = intent.getIntExtra("MSG", 0);            //播放信息
        if (msg == PlayerMSG.MSG.PLAY_MSG) {    //直接播放音樂
            play(0);
        } else if (msg == PlayerMSG.MSG.PAUSE_MSG) {    //暫停
            pause();
        } else if (msg == PlayerMSG.MSG.STOP_MSG) {        //停止
            stop();
        } else if (msg == PlayerMSG.MSG.CONTINUE_MSG) {    //繼續播放
            resume();
        } else if (msg == PlayerMSG.MSG.PRIVIOUS_MSG) {    //上一首
            previous();
        } else if (msg == PlayerMSG.MSG.NEXT_MSG) {        //下一首
            next();
        } else if (msg == PlayerMSG.MSG.PROGRESS_CHANGE) {    //進度更新
            currentTime = intent.getIntExtra("progress", -1);
            play(currentTime);
        } else if (msg == PlayerMSG.MSG.PLAYING_MSG) {
            mHandler.sendEmptyMessage(1);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void play(int currentTime) {
        try {

            mediaPlayer.reset();// 把各項參數恢復到初始狀態
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare(); // 進行緩沖
            mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime));// 注冊一個監聽器
            //更新播放狀態
            Intent intent = new Intent(PLAY_STATUE);
            // 發送播放完畢的信號,更新播放狀態
            intent.putExtra("playstatue", true);
            sendBroadcast(intent);
            mHandler.sendEmptyMessage(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //繼續播放
    private void resume() {
        if (isPause) {
            mediaPlayer.start();
            isPause = false;
        }
    }

    /**
     * 上一首
     */
    private void previous() {
        Intent sendIntent = new Intent(UPDATE_ACTION);
        sendIntent.putExtra("position", position);
        // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);
        play(0);
    }

    /**
     * 下一首
     */
    private void next() {
        Intent sendIntent = new Intent(UPDATE_ACTION);
        sendIntent.putExtra("position", position);
        // 發送廣播,將被Activity組件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);
        play(0);
    }

    private void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPause = true;
        }
    }

    private void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare(); // 在調用stop後如果需要再次通過start進行播放,需要之前調用prepare函數
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 實現一個OnPrepareLister接口,當音樂准備好的時候開始播放
     */
    private final class PreparedListener implements MediaPlayer.OnPreparedListener {
        private int currentTime;

        public PreparedListener(int currentTime) {
            this.currentTime = currentTime;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start(); // 開始播放
            if (currentTime > 0) { // 如果音樂不是從頭播放
                mediaPlayer.seekTo(currentTime);
            }
            Intent intent = new Intent();
            intent.setAction(MUSIC_DURATION);
            duration = mediaPlayer.getDuration();
            intent.putExtra("duration", duration);    //通過Intent來傳遞歌曲的總長度
            sendBroadcast(intent);
        }
    }

    protected int getRandomIndex(int end) {
        int index = (int) (Math.random() * end);
        return index;
    }


    public class MusicReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int control = intent.getIntExtra("control", -1);
            switch (control) {
                case 0:
                    palyflag = 0; // 順序播放
                    break;
                case 1:
                    palyflag = 1;    //列表循環
                    break;
                case 2:
                    palyflag = 2;    //單曲循環
                    break;
                case 3:
                    palyflag = 3;  //隨機
                    break;
                default:
                    break;
//            if(action.equals(SHOW_LRC)){
//                current = intent.getIntExtra("listPosition", -1);
//                initLrc();
            }
        }
    }


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        //當綁定後,返回一個musicBinder
        return musicBinder;
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }
}

這些函數裡面有個標識,其實有時候,我們並不想通過new一個類來處理信息,這個就是個很好的表示來解決問題。
PlayerMSG.java

package com.flashmusic.tool;

/**
 * Created by zhouchenglin on 2016/4/18.
 */
public class PlayerMSG {
    public class MSG{
        public static final int PLAY_MSG = 1;       //播放
        public static final int PAUSE_MSG = 2;      //暫停
        public static final int STOP_MSG = 3;       //停止
        public static final int CONTINUE_MSG = 4;   //繼續
        public static final int PRIVIOUS_MSG = 5;   //上一首
        public static final int NEXT_MSG = 6;       //下一首
        public static final int PROGRESS_CHANGE = 7;//進度改變
        public static final int PLAYING_MSG = 8;    //正在播放
    }
}

 

   

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