我如何在Android中拥有一个mediaPlayer来一个接一个地播放2个或更多mp3文件?
作者:互联网
我正在创建一个我希望它一个接一个地播放多个mp3文件的android应用程序.
我的应用程序上有一个mediaPlayer,如何设置播放mp3文件的队列?
解决方法:
实现此目的的方法是创建一个实现OnCompletionListener的类,该类处理onCompletion并接收下一个要播放的文件.
首先像下面这样定义PlayMedia的类:
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
@Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
然后像这样使用PlayMedia:
int[] soundIDs = {R.raw.firstmp3, R.raw.secondmp3};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
标签:android-mediaplayer,android 来源: https://codeday.me/bug/20191027/1944499.html