达内课程-音乐播放器v1.0(中)

学习了达内课程-音乐播放器v1.0(上)我们接着完善我们的代码

MediaPlayer类支持主流的音频、视频格式播放

常用方法:
void reset()//重置
void setDataSource(String)//设置数据源,参数可以是音频/视频路径
void prepare()//加载音频/视频数据,必须在setDataSource()方法后调用
void start()//开始播放,必须在prepare()方法后调用
void stop()//停止播放
int getCurrentPosition;//获取当前播放到的位置,返回值毫秒
void seekTo(int);//快进到指定位置,参数是毫秒为单位的数值

效果图

达内课程-音乐播放器v1.0(中)_第1张图片

代码

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/ll_music_info"/>

    <LinearLayout
        android:id="@+id/ll_music_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ll_buttons"
        android:padding="10dp">

        <TextView
            android:id="@+id/tv_current_music_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="请选择播放歌曲"/>

    LinearLayout>

    <LinearLayout
        android:id="@+id/ll_buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        >

        <ImageButton
            android:id="@+id/ib_previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_media_previous"
            />
        <ImageButton
            android:id="@+id/ib_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Play"
            android:src="@android:drawable/ic_media_play"/>
        <ImageButton
            android:id="@+id/ib_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next"
            android:src="@android:drawable/ic_media_next"/>

    LinearLayout>

RelativeLayout>

item_music.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv_music_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="title"
        android:textColor="#222222"
        android:textSize="15dp"
        />

    <TextView
        android:id="@+id/tv_music_path"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:maxLines="1"
        android:layout_below="@+id/tv_music_title"
        android:text="path......"
        android:textColor="#999999"
        android:textSize="15dp"
        />
RelativeLayout>

MainActivity

public class MainActivity extends AppCompatActivity {
    private List musics;
    private ListView listView;
    private MusicAdapter adapter;
    private TextView tvCurrentMusicTitle;

    private ImageButton ibPrevious;//上一首按钮
    private ImageButton ibPlay;//播放/暂停按钮
    private ImageButton ibNext;//下一首按钮
    private MediaPlayer mediaPlayer;
    private int pausePosition;//歌曲暂停时间
    private int currentMusicIndex;//当前播放歌曲索引
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        musics = new ArrayList();
        ibPrevious  = findViewById(R.id.ib_previous);
        ibPlay = findViewById(R.id.ib_play);
        ibNext = findViewById(R.id.ib_next);
        tvCurrentMusicTitle = findViewById(R.id.tv_current_music_title);
        listView = findViewById(R.id.listview);
        mediaPlayer = new MediaPlayer();

        //为底部按钮添加点击事件
        InnerClassOnClickListener listener = new InnerClassOnClickListener();
        ibPrevious.setOnClickListener(listener);
        ibPlay.setOnClickListener(listener);
        ibNext.setOnClickListener(listener);

        //为listview添加点击事件
        OnItemClickListener onItemClickListener = new OnItemClickListener();
        listView.setOnItemClickListener(onItemClickListener);

        //获取数据
        getData();

        //通过日志检查歌曲数据集合
        for(int i=0;i"MUSIC",""+musics.get(i));
        }

        adapter = new MusicAdapter(MainActivity.this,musics);
        listView.setAdapter(adapter);

    }

    //获取sd卡下的文件
    private void getData(){
        //【目标】扫描sd卡下的Music文件夹,获取所有歌曲信息
        //1、获取sdcard下的Music文件夹的File对象
        //2、检查Music文件夹是否存在
        //3、获取Music文件夹下的文件列表
        //4、检查文件列表是否有效
        //5、遍历文件列表
        //5.1、检查是否是文件
        //5.2、检查是否是mp3文件
        //String musicPath = "/storage/emulated/0/Music/";
        //File musicDir = new File(musicPath);

        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

            File musicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);

            if (musicDir.exists()) {
                Log.d("MUSIC", "【信息】文件夹存在");
                File[] files = musicDir.listFiles();
                if (files != null && files.length > 0) {
                    Log.d("MUSIC", "【信息】文件夹列表有效");
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].isFile()) {
                            String fileName = files[i].getName();
                            if (fileName.toLowerCase().endsWith(".mp3")) {
                                Music music = new Music();
                                music.setPath(files[i].getAbsolutePath());
                                music.setTitle(files[i].getName());
                                musics.add(music);

                                Log.d("MUSIC", files[i].getAbsolutePath());
                            } else {
                                Log.w("MUSIC", "【错误】当前遍历到的不是mp3文件");
                            }
                        } else {
                            Log.w("MUSIC", "【错误】当前遍历到的第" + i + "个不是文件");
                        }
                    }
                } else {
                    Log.w("MUSIC", "【错误】文件夹列表无效");
                }
            } else {
                Log.w("MUSIC", "【错误】文件夹不存在");
            }
        }else{
            Log.w("MUSIC", "【错误】SDCARD不可用");
        }
    }

    //按钮监听
    private class InnerClassOnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.ib_previous:
                    previous();
                    break;
                case R.id.ib_play:
                    if(mediaPlayer.isPlaying()){
                        pause();
                    }else {
                        play();
                    }
                    break;
                case R.id.ib_next:
                    next();
                    break;
            }
        }
    }

    //listview监听
    private class OnItemClickListener implements AdapterView.OnItemClickListener{

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

    //播放
    private void play(){

        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(musics.get(currentMusicIndex).getPath());
            mediaPlayer.prepare();
            mediaPlayer.seekTo(pausePosition);
            mediaPlayer.start();

            ibPlay.setImageResource(android.R.drawable.ic_media_pause);
            tvCurrentMusicTitle.setText("当前歌曲:"+musics.get(currentMusicIndex).getTitle());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //方法重载
    private void play(int position){
        currentMusicIndex = position;
        pausePosition = 0;
        play();
    }

    //暂停
    private void pause(){
        pausePosition = mediaPlayer.getCurrentPosition();
        mediaPlayer.pause();
        ibPlay.setImageResource(android.R.drawable.ic_media_play);
    }
    //下一首
    private void next(){
        currentMusicIndex++;
        if(currentMusicIndex>musics.size()-1){
            currentMusicIndex = 0;
        }
        //清空暂停时间
        pausePosition = 0;
        play();
    }
    //下一首
    private void previous(){
        currentMusicIndex--;
        if(currentMusicIndex<0){
            currentMusicIndex = musics.size()-1;
        }
        //清空暂停时间
        pausePosition = 0;
        play();
    }
}

MusicAdapter

public class MusicAdapter extends BaseAdapter {
    private List data;
    private Context context;

    public MusicAdapter(Context context,List data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Music music = data.get(i);

        if(view == null){
            LayoutInflater inflater = LayoutInflater.from(context);
            view = inflater.inflate(R.layout.item_music,null);
        }
        String fileName = music.getTitle();
        TextView tv_music_path = view.findViewById(R.id.tv_music_path);
        TextView tv_music_title = view.findViewById(R.id.tv_music_title);
        tv_music_path.setText(music.getPath());
        tv_music_title.setText(fileName.substring(0,fileName.lastIndexOf(".")));

        return view;
    }


    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }
}

Music

public class Music {
    private String path;
    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String toString() {
        return "Music Title ["+title+"] Music Path ["+path+"]";
    }
}

你可能感兴趣的:(#,达内安卓培训,mediaplayer)