设计一个音乐播放器,用List列表显示手机中所有音乐,支持播放、暂停、继续、上一首、下一首等功能。

package com.example.lenovo.musicplayer;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.ActivityCompat;


import java.text.SimpleDateFormat;
import java.util.ArrayList;




public class MusicActivity extends Activity {

    ArrayList musicList = new ArrayList(); //音乐列表
    MediaPlayer mp=new MediaPlayer(); //音乐播放器
    SeekBar seekBar;
    TextView current_time, total_time; //显示当前音乐进度信息
    ImageButton btn_play; //播放按钮
    ImageButton btn_left;
    ImageButton btn_right;

    TextView playtitle;

    int position1=0;
    int count=0;

    int duration=0; //获取时长(ms)
    int current=0; //当前音乐播放位置
    boolean isOver=false; //是否播放完毕
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if ( msg.what == 0 ) {
                if( ! isOver ) {
                    current = mp.getCurrentPosition();
                    seekBar.setProgress(current);
                    SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                    String time=sdf.format(current);
                    current_time.setText(""+time); //""不要掉了
                }
            }
        }
    };
    public ArrayList ScannerMusic() {
        ArrayList list=new ArrayList<>();
        //  查询媒体数据库
        Cursor cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                MediaStore.Audio.Media.TITLE); //按标题排序
        // 遍历媒体数据库
        if ( cursor.moveToFirst() ){ //遍历每一行
            while ( !cursor.isAfterLast() ) { //遍历每一列
                //歌曲IDMediaStore.Audio.Media._ID
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                //歌曲的名称 :MediaStore.Audio.Media.TITLE
                String tilte =cursor.getString(
                        cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));

                //歌曲作者
                String artist=cursor.getString(
                        cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));

                //歌曲路径 :MediaStore.Audio.Media.DATA
                String url = cursor.getString(
                        cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                //歌曲时长 :MediaStore.Audio.Media.DURATION
                int duration = cursor.getInt(
                        cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                Music m = new Music(id, tilte,artist, url, duration);
                list.add(m);
                cursor.moveToNext();
            } //end while
            cursor.close();
        } //end if
        return list;
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        //初始化
        if (ActivityCompat.checkSelfPermission( MusicActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(MusicActivity.this,
                    new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 123);
            return;
        }
        seekBar=(SeekBar)findViewById(R.id.musicSeekBar);
        current_time=(TextView)findViewById(R.id.current_time);
        total_time=(TextView)findViewById(R.id.total_time);
        btn_play=(ImageButton)findViewById(R.id.btn_play);
        btn_right=(ImageButton)findViewById(R.id.btn_right);
        btn_left=(ImageButton)findViewById(R.id.btn_left);
        playtitle=(TextView)findViewById(R.id.playtitle);
        // 获取音乐列表
        musicList=ScannerMusic();
        // 使用MusicAdpater
        MusicAdapter adapter = new MusicAdapter(
                MusicActivity.this, R.layout.music_item, musicList );
        ListView li=(ListView)findViewById(R.id.musicListView);
        li.setAdapter(adapter);
        count=li.getCount();
        li.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                position1=position;

                Music m=musicList.get(position);
                playtitle.setText("正在播放:"+m.getTitle());

                String music_url=m.getUrl(); //获得音乐路径
                isOver=false;
               btn_play.setImageResource(R.drawable.play);
                try{
                    mp.reset(); // 重置
                    mp.setDataSource(music_url);
                    mp.prepare(); // 准备
                }catch (Exception e){
                    e.printStackTrace();
                }
                duration=mp.getDuration(); //获取音乐时长(ms)
                SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                String time=sdf.format(duration);
                total_time.setText(""+time);
                seekBar.setMax(duration); //SeekBar设置最大时长
                mp.start(); //播放
                btn_play.setImageResource(R.drawable.pause);
                new Thread() {
                    @Override
                    public void run() {
                        while ( ! isOver ) {
                            try {
                                Thread.sleep(50); //50ms执行一次mTimerTask任务
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mHandler.sendEmptyMessage(0); //直接发送一个what=0的空消息
                        }
                    }
                }.start();
            } //end onItemClick
        }); //end setOnItemClick
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isOver=false;
                if( mp.isPlaying() ){
                    mp.pause();
                    btn_play.setImageResource(R.drawable.play);
                }else{
                    mp.start();
                    btn_play.setImageResource(R.drawable.pause);
                    //后续,再次启动子线程
                    new Thread() {
                        @Override
                        public void run() {
                            while ( !isOver ) {
                                try {
                                    Thread.sleep(50); //50ms执行一次mTimerTask任务
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                mHandler.sendEmptyMessage(0); //直接发送一个what=0的空消息
                            }
                        }
                    }.start();
                } //end else
            } //end onClick
        }); //end setOnClick
        // 播放完毕
        btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position1+=1;
                if(position1>=count)
                {
                    position1=0;
                }
                Music m=musicList.get(position1);

                playtitle.setText("正在播放:"+m.getTitle());
                String music_url=m.getUrl(); //获得音乐路径
                isOver=false;
                btn_play.setImageResource(R.drawable.pause);
                try{
                    mp.reset(); // 重置
                    mp.setDataSource(music_url);
                    mp.prepare(); // 准备
                }catch (Exception e){
                    e.printStackTrace();
                }
                duration=mp.getDuration(); //获取音乐时长(ms)
                SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                String time=sdf.format(duration);
                total_time.setText(""+time);
                seekBar.setMax(duration); //SeekBar设置最大时长
                mp.start(); //播放
                new Thread() {
                    @Override
                    public void run() {
                        while ( !isOver ) {
                            try {
                                Thread.sleep(50); //50ms执行一次mTimerTask任务
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mHandler.sendEmptyMessage(0); //直接发送一个what=0的空消息
                        }
                    }
                }.start();
            }
        });
        btn_left.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                position1-=1;
                if(position1<=0)
                {
                    position1=count-1;
                }
                Music m=musicList.get(position1);

                playtitle.setText("正在播放:"+m.getTitle());
                String music_url=m.getUrl(); //获得音乐路径
                isOver=false;
                btn_play.setImageResource(R.drawable.pause);
                try{
                    mp.reset(); // 重置
                    mp.setDataSource(music_url);
                    mp.prepare(); // 准备
                }catch (Exception e){
                    e.printStackTrace();
                }
                duration=mp.getDuration(); //获取音乐时长(ms)
                SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                String time=sdf.format(duration);
                total_time.setText(""+time);
                seekBar.setMax(duration); //SeekBar设置最大时长
                mp.start(); //播放
                new Thread() {
                    @Override
                    public void run() {
                        while ( !isOver ) {
                            try {
                                Thread.sleep(50); //50ms执行一次mTimerTask任务
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mHandler.sendEmptyMessage(0); //直接发送一个what=0的空消息
                        }
                    }
                }.start();

            }
        });



        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                position1+=1;
                if(position1>=count)
                {
                    position1=0;
                }
                Music m=musicList.get(position1);
                playtitle.setText("正在播放:"+m.getTitle());
                String music_url=m.getUrl(); //获得音乐路径
                isOver=false;
                btn_play.setImageResource(R.drawable.pause);
                try{
                    mp.reset(); // 重置
                    mp.setDataSource(music_url);
                    mp.prepare(); // 准备
                }catch (Exception e){
                    e.printStackTrace();
                }
                duration=mp.getDuration(); //获取音乐时长(ms)
                SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                String time=sdf.format(duration);
                total_time.setText(""+time);
                seekBar.setMax(duration); //SeekBar设置最大时长
                mp.start(); //播放
                new Thread() {
                    @Override
                    public void run() {
                        while ( !isOver ) {
                            try {
                                Thread.sleep(50); //50ms执行一次mTimerTask任务
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mHandler.sendEmptyMessage(0); //直接发送一个what=0的空消息
                        }
                    }
                }.start();
            }
        });
        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) {
                current=seekBar.getProgress();
                current_time.setText(""+current);
                mp.seekTo(current);
            }
        }); //end setOnSeekBar
    } // end onCreate
   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if( keyCode==event.KEYCODE_BACK ){
            new AlertDialog.Builder(MusicActivity.this)
                    .setIcon(R.drawable.login)
                    .setTitle("提示")
                    .setMessage("确定退出吗?")
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        isOver=true;
        if( mp!=null ){
            mp.stop();
            mp.release();
        }
        Toast.makeText(getApplicationContext(), "退出啦", Toast.LENGTH_SHORT).show();
    }
} // end activity(完)

你可能感兴趣的:(设计一个音乐播放器,用List列表显示手机中所有音乐,支持播放、暂停、继续、上一首、下一首等功能。)