Android第三次作业
一、实验截图
功能:
实现播放,暂停,停止,播放上一首,下一首功能
显示播放列表
至少可以播放3首歌曲
成果
二、关键代码
1.获取本地音乐用list存储
2.扫描并存储歌曲信息(歌曲名,歌手,歌曲长度,歌曲的大小)
public static List<Song> getMusicData(Context context) {
List<Song> list = new ArrayList<Song>();
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
null, MediaStore.Audio.AudioColumns.IS_MUSIC);
if (cursor != null) {
for(int i = 0; i <cursor.getCount();i++) {
Song song =new Song();
song.song=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
song.singer=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
song.path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
song.duration=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
song.size=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
list.add(song);
}
cursor.close();
}
return list;
3.用类封装歌曲信息(歌手,歌曲名,歌曲的地址,歌曲长度,歌曲的大小)
public class Song {
public String singer;
public String song;
public String path;
public int duration;
public long size;
}
4.为listview组件创建并关联适配器
mListView = (ListView) findViewById(R.id.main_listview);
list = new ArrayList<>();
list = MusicUtils.getMusicData(this);
adapter = new Adapter(this,list);
mListView.setAdapter(adapter);
5.获取歌曲位置,从而切换歌曲
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Position=i;
changeMusic(Position);
}
private void changeMusic(int position){
if (position<0){
Position = position =list.size()-1;
}
else if (position>list.size()-1){
Position = position=0;
}
if (mediaPlayer==null){
mediaPlayer=new MediaPlayer();
}
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(list.get(position).path); // 设置播放源
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
// 切歌时重置进度条并展示歌曲时长
mSeekBar.setProgress(0);
mSeekBar.setMax(mediaPlayer.getDuration());
mTotalTimeTv.setText(parseTime(mediaPlayer.getDuration()));
updateProgress();
}
三、apk安装效果
四、代码链接
源码:[https://git.dev.tencent.com/mengfanmao/android-third-work.git]
apk链接:[https://git.dev.tencent.com/mengfanmao/android-third-work.git]