安卓第十七天笔记--简易版本音乐播放器

Posted 森林森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓第十七天笔记--简易版本音乐播放器相关的知识,希望对你有一定的参考价值。


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;
            }
        }
    }

 

以上是关于安卓第十七天笔记--简易版本音乐播放器的主要内容,如果未能解决你的问题,请参考以下文章

Android简易音乐重构MVVM Java版-新增歌曲播放界面+状态栏黑科技(十七)

pyqt5实现一个简易音乐播放器(升级到v2版本)

做一个简易的音乐播放器

安卓第十六天笔记-音频与视频播放

Android制作简易的音乐播放器和视频播放器

Android制作简易的音乐播放器和视频播放器