Android第三次作业
1、实现功能:播放,暂停,停止,下一首,上一首,列表播放,可播放五首音乐。
2、截图:
3、关键代码
播放,暂停,停止,下一首,上一首代码:
public void onClick(View v) { switch (v.getId()){ //暂停或播放 case R.id.play : case R.id.pause: if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); }else{ mediaPlayer.start(); } break; //停止 case R.id.stop: if(mediaPlayer.isPlaying()){ mediaPlayer.reset(); initMediaPlayer();//初始化播放器 MediaPlayer } break; //下一首 case R.id.next: if(musicIndex < 4){ mediaPlayer.stop(); mediaPlayer.reset(); musicIndex++; initMediaPlayer(); mediaPlayer.start(); }else{ Toast.makeText(this, "当前已经是最后一首歌曲了", Toast.LENGTH_SHORT).show(); } break; //上一首 case R.id.pre: if( musicIndex > 0){ mediaPlayer.stop(); mediaPlayer.reset(); musicIndex--; initMediaPlayer(); mediaPlayer.start(); }else{ Toast.makeText(this, "当前已经是第一首歌曲了", Toast.LENGTH_SHORT).show(); } break; default: break; }
初始化播放:
private void initMediaPlayer() { try { File file = new File(Environment.getExternalStorageDirectory(),musicDir[musicIndex]); mediaPlayer.setDataSource(file.getPath()); mediaPlayer.setLooping(true); mediaPlayer.prepare(); } catch (Exception e) { e.printStackTrace(); } }
列表音乐播放:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { musicIndex = position; try{ mediaPlayer.reset(); File file = new File(Environment.getExternalStorageDirectory(),musicDir[musicIndex]); mediaPlayer.setDataSource(file.getPath()); mediaPlayer.setLooping(true); mediaPlayer.prepare(); mediaPlayer.start(); }catch (Exception e){ } } });
4、代码链接:
5、apk地址:
无效请看录屏: