Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 安卓第十七天筆記--簡易版本音樂播放器,安卓第十七天

安卓第十七天筆記--簡易版本音樂播放器,安卓第十七天

編輯:關於android開發

安卓第十七天筆記--簡易版本音樂播放器,安卓第十七天



title:簡易版本音樂播放器

簡易版本音樂播放器

1.布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/musicList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#86B2F4"
        android:text="音樂文件列表"
        android:textColor="#fff"
        android:textSize="28sp"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <ImageButton
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/stop"/>

        <ImageButton
            android:id="@+id/pre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/pree"/>

        <ImageButton
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/play"/>

        <ImageButton
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/next"/>
    </LinearLayout>
</LinearLayout>

 

2.工具類

/**
 * Created by  劉楠 on 2016-03-05 19:39.
 * 文件過濾器工具類,
 * 用於過濾指定後綴的文件
 */
public class MusicFileNameFilter implements FilenameFilter {

    private String type;

    public MusicFileNameFilter(String type) {
        this.type = type;
    }

    @Override
    public boolean accept(File dir, String filename) {
        return filename.endsWith(type);
    }
}

 

3.Binder接口

/**
 * Created by  劉楠 on 2016-03-05 20:41.
 */
public interface IMusicPlayerService {
    public void callplay(String path);
    ;
    public  void callStop();

    public boolean callIsPlaying();

    public int callGetgetDuration();

    public int callGetgetCurrentDuration();

    public boolean callMediaIsNull();

    public void callChanageSeek(int position);

    public void callPause();
}
4. service

            /**
         * Created by  劉楠 on 2016-03-05 20:32.
         *
         * Servie音樂播放
         */
        public class MusicPlayerService extends Service {


            private MediaPlayer mediaPlayer;

            private MusicPlayerBinder musicPlayerBinder = new MusicPlayerBinder();

            private class MusicPlayerBinder extends Binder implements IMusicPlayerService {

                public void callplay(String path) {

                    play(path);
                }

                @Override
                public void callStop() {
                    stop();
                }

                @Override
                public boolean callIsPlaying() {
                    return isPlaying();
                }

                @Override
                public int callGetgetDuration() {
                    return getgetDuration();
                }

                @Override
                public int callGetgetCurrentDuration() {
                    return getCurrentDuration();
                }

                @Override
                public boolean callMediaIsNull() {
                    return mediaIsNull();
                }

                @Override
                public void callChanageSeek(int position) {
                    chanageSeek(position);
                }

                @Override
                public void callPause() {
                    pause();
                }

            }

            @Nullable
            @Override
            public IBinder onBind(Intent intent) {

                return musicPlayerBinder;
            }

            /**
             * 初始化
             * @param path
             */
            private void init(String path) {

                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                    reset(path);
                }else{
                    reset(path);
                }
            }

            /**
             * 資源重置
             * @param path
             */
            private void reset(String path) {

                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(path);
                        mediaPlayer.prepare();
                        mediaPlayer.setLooping(true);
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

            }

            /**
             * 播放
             * @param path
             */
            private void play(String path) {

              /*  if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else if (mediaPlayer != null&&!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                } else {
                    init(path);
                }*/
                init(path);

            }

            /**
             * 是不是在播放
             * @return
             */
            private boolean isPlaying(){
                if(mediaPlayer!=null) {
                    return mediaPlayer.isPlaying();
                }
                return false;
            }

            /**
             * 獲取總的進度
             * @return
             */
            private int getgetDuration(){
                return  mediaPlayer.getDuration();
            }

            /**
             * 獲取當前進度
             * @return
             */
            private int getCurrentDuration(){
                return mediaPlayer.getCurrentPosition();
            }

            /**
             * 暫停
             */
            private void pause(){
                if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }else if(mediaPlayer!=null&&!mediaPlayer.isPlaying()){
                    mediaPlayer.start();
                }
            }

            /**
             * 停止
             */
            private void stop(){
                if(mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer=null;

                }
            }

            /**
             * 判斷當前是不是NULL
             * @return
             */
            private boolean mediaIsNull(){
                return  mediaPlayer==null;
            }

            private void chanageSeek(int position){
                mediaPlayer.seekTo(position);
                mediaPlayer.start();
            }


        }

 

5.Activity

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
        //音樂文件的目錄
        private static final String PATH = Environment.getExternalStorageDirectory() + "/Music/";
        private static final String TAG = "MainActivity";
        //文件路徑
        private ArrayList<String> fileList = new ArrayList<String>();
        //文件名
        private ArrayList<String> fileNameList = new ArrayList<String>();

        /*
        進度條
         */
        private SeekBar seekBar;
        /*
        音樂文件列表
         */
        private Button musicList;

        /*
        音樂控制按鍵
         */
        private ImageButton stop;
        private ImageButton pre;
        private ImageButton play;
        private ImageButton next;
        //單首音樂的路徑
        private String musicPath;

        private IMusicPlayerService mPlayerService;

        private MusicPlayerServiceConnection mConn;

        private boolean mBound =false;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            /*
            初始化
             */
            seekBar = (SeekBar) findViewById(R.id.seekBar);

            musicList = (Button) findViewById(R.id.musicList);

            stop = (ImageButton) findViewById(R.id.stop);
            pre = (ImageButton) findViewById(R.id.pre);
            ;
            play = (ImageButton) findViewById(R.id.play);
            ;
            next = (ImageButton) findViewById(R.id.next);
            ;


            File file = new File(PATH);

            //獲取文件列表
            File[] arrs = file.listFiles(new MusicFileNameFilter(".mp3"));

            for (File f : arrs) {
                //添加全路徑到文件列表
                fileList.add(f.getAbsolutePath());
                //添加文件表到文件列表
                fileNameList.add(f.getName());

            }

            /*
            設置監聽器
             */
            musicList.setOnClickListener(this);
            stop.setOnClickListener(this);
            pre.setOnClickListener(this);
            play.setOnClickListener(this);
            next.setOnClickListener(this);



            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }
                //拖動進度條,改變播放進度
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mPlayerService.callChanageSeek(seekBar.getProgress());
                }
            });

        }

        @Override
        protected void onStart() {
            super.onStart();
            if(mConn==null){
                mConn= new MusicPlayerServiceConnection();
            }
            Intent intent = new Intent(this,MusicPlayerService.class);
            mBound = bindService(intent, mConn, BIND_AUTO_CREATE);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.musicList:
                    showList();
                    break;
                case R.id.stop:
                    stop();
                    break;
                case R.id.pre:
                    pre();
                    break;
                case R.id.play:
                    play();
                    break;
                case R.id.next:
                    next();
                    break;
            }

        }
        /*
        下一首
         */
        private void next() {
            int index = fileList.indexOf(musicPath);
            if(index>=fileList.size()){
                index=0;
            }
            mPlayerService.callplay(fileList.get(index+1));
        }

        /*
        播放
         */
        private void play() {
            Log.d(TAG, "mBound" + mBound);
            boolean isNull = mPlayerService.callMediaIsNull();
            if(isNull) {
                mPlayerService.callplay(musicPath);
            }else{
                mPlayerService.callPause();
            }

            if(mPlayerService.callIsPlaying()){
                play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
            }else{
                play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));
            }

            //更新進度
            new Thread(){

                boolean isFinished=mPlayerService.callIsPlaying();
                @Override
                public void run() {
                    if(isFinished) {
                        while (isFinished) {
                            SystemClock.sleep(200);
                            int currentDuration = mPlayerService.callGetgetCurrentDuration();
                            int duration = mPlayerService.callGetgetDuration();
                            seekBar.setMax(duration);
                            seekBar.setProgress(currentDuration);
                            if (currentDuration >= duration) {
                                isFinished = false;
                            }
                        }
                    }

                }
            }.start();
        }

        /**
         * 上一首
         */
        private void pre() {
            int index = fileList.indexOf(musicPath);
            if(index<=0){
                index=fileList.size()-1;
            }
            mPlayerService.callplay(fileList.get(index-1));
        }

        /**
         * 停止播放
         */
        private void stop() {
            mPlayerService.callStop();
        }

        /**
         * 顯示音樂列表
         */
        private void showList() {

            Intent intent = new Intent(this,MusicListActivity.class);
            //intent.putStringArrayListExtra("filelist",fileList);
            intent.putStringArrayListExtra("filenamelist",fileNameList);

            startActivityForResult(intent,100);

        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if(data==null){
                Toast.makeText(MainActivity.this, "沒有結果", Toast.LENGTH_SHORT).show();
                return;
            }
            //獲取下標
            int position = data.getIntExtra("position", 0);
            //設置音樂路徑
            musicPath = fileList.get(position);
           // play();
            Log.d(TAG,musicPath);
        }

        private class MusicPlayerServiceConnection implements ServiceConnection{

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mPlayerService = (IMusicPlayerService) service;


            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                if(mConn!=null){
                 mConn =null;
                }
            }
        }

        @Override
        protected void onStop() {
            super.onStop();
            if(mConn!=null){
                unbindService(mConn);
                mConn=null;
                mPlayerService=null;
            }
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            if(mConn!=null){
                unbindService(mConn);
                mConn=null;
                mPlayerService=null;
            }
        }
    }

 

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