有序播放,并且同一种提示音在相同时间段只会播放一次
import android.media.MediaPlayer;
import android.net.Uri;
import java.util.ArrayList;
/**
* Created by junjie on 2016/3/31.
*/
public class MediaPlayerUtil {
private static MediaPlayer player;
private static ArrayList<Integer> resources;
private static MyOnCompletionListener myOnCompletionListener;
private static int lastMedia;
public static void init(){
if(player != null){
return;
}
player = new MediaPlayer();
resources = new ArrayList<>();
myOnCompletionListener = new MyOnCompletionListener();
player.setOnCompletionListener(myOnCompletionListener);
}
public static void release(){
if(player == null){
return;
}
player.setOnCompletionListener(null);
if(player.isPlaying()){
player.stop();
}
player.release();
player = null;
myOnCompletionListener = null;
resources.clear();
resources = null;
}
public static void addresource(int resource){
if(player == null){
init();
}
//当前正在播放这条语音 或者 集合中已经有了这条语音,不重复播放
if((player.isPlaying() && lastMedia == resource) || resources.contains(resource)){
return;
}
resources.add(resource);
readyPlayer();
}
public static void addresources(ArrayList<Integer> _resources){
resources.addAll(_resources);
readyPlayer();
}
private static void readyPlayer(){
if(!player.isPlaying()){
playAndSetData();
}
}
static class MyOnCompletionListener implements MediaPlayer.OnCompletionListener {
@Override
public void onCompletion(MediaPlayer mp) {
playAndSetData();
}
}
private static void playAndSetData(){
try{
if(resources.size() == 0){
lastMedia = 0;
return;
}
player.reset();
player.setDataSource(AppContextUtil.getAppContext(), Uri.parse("android.resource://"
+ AppContextUtil.getAppContext().getPackageName() + "/" + resources.get(0)) );
lastMedia = resources.get(0);
resources.remove(0);
player.prepare();
player.start();
}catch (Exception e){
e.printStackTrace();
}
}
}