安卓第三次作业:音乐播放器
姓名:李洪岩
班级:计算机164
学号:1600802119
代码链接:https://git.coding.net/huimoudinggeren/MyApplication.git
APK链接:https://coding.net/u/huimoudinggeren/p/MyApplication/git/blob/master/app-debug.apk
实现功能:上一曲、下一曲、暂停、开始(由于并没有实现读取SD卡内存的功能,运行代码时,需要在项目中手动添加音乐。)
关键代码:
list.add("music.mp3");
list.add("music1.mp3");
list.add("music2.mp3");
mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource("/storage/sdcard/Music/music.mp3");//指定音频文件路径
mediaPlayer.prepare();//让mediaPlayer进入准备状态
} catch (IOException e) {
e.printStackTrace();
}
}
private void cut_music(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("/storage/sdcard/Music/"+list.get(position));
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.last:
cut_music(--position);
break;
case R.id.play:
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();//开始播放
}
break;
case R.id.pause:
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();//暂停播放
}
break;
case R.id.stop:
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();//停止播放
}
break;
case R.id.next:
cut_music(++position);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}