本代码为教学材料,仅作学习使用,分析在注释里。
1.调用代码(RingDataAdapter)
public void togglePosition(int position,String curMusic) {
if (expandPosition != position) {
//此方法可以中途切换mp3播放 begin
MyMediaPlayer myMediaPlayer=MyMediaPlayer.getInstance();
myMediaPlayer.setCurMusic(curMusic);
myMediaPlayer.playMusic();
notifyItemChanged(expandPosition);
//此方法可以中途切换mp3播放 end
expandPosition = position;
} else {
expandPosition = -1;
}
notifyItemChanged(position);
}
2.播放MP3核心代码(MyMediaPlayer)单例实现
package cn.fowit.xshow.utils;
import android.media.MediaPlayer;
import android.os.Handler;
public class {
private MediaPlayer mediaPlayer;
//放音频路径
private String curMusic = "";
private static volatile MyMediaPlayer instance = null;
private MyMediaPlayer() { }
public static MyMediaPlayer getInstance() {
if (instance == null) {
synchronized (MyMediaPlayer.class) {
if (instance == null) {
instance = new MyMediaPlayer();
}
}
}
return instance;
}
//此方法可以中途切换音频
public void playMusic(){
try{
if (mediaPlayer==null){
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(curMusic);
mediaPlayer.prepare();
mediaPlayer.start();
}else if (mediaPlayer.isPlaying()){
mediaPlayer.stop();
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
try{
mediaPlayer.reset();
mediaPlayer.setDataSource(curMusic);
mediaPlayer.prepare();
mediaPlayer.start();
}catch (Exception e){
curMusic = "";
e.printStackTrace();
}
}
}, 1000);
}else{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(curMusic);
mediaPlayer.prepare();
mediaPlayer.start();
}
}catch (Exception e){
curMusic = "";
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
curMusic = "";
}
});
}
public void mediaPlayerStop(){
//停止音乐播放
if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
public String getCurMusic() {
return curMusic;
}
public void setCurMusic(String curMusic) {
this.curMusic = curMusic;
}
}
|