java-MediaPlayer是否可以播放一个音频文件,完成后可以播放另一个音频文件?
作者:互联网
我希望MediaPlayer接受songTitles的数组列表,并检查传入的歌曲名称,然后播放该歌曲.完成后,我希望它转到循环中的下一个歌曲标题并播放该歌曲.但是,我的代码只播放最后一首歌.
public void play(Context c, ArrayList<String> songTitles) {
stop();
for (String song: songTitles){
if (song.equalsIgnoreCase("shakeItOff")){
mSongPlayer = MediaPlayer.create(c, R.raw.shaketoff);
} else if (song.equalsIgnoreCase("dropItLow")){
mSongPlayer = MediaPlayer.create(c, R.raw.dropitlow);
} else if (song.equalsIgnoreCase("chachaslide")){
mSongPlayer = MediaPlayer.create(c, R.raw.chachaslide);
}
mSongPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp == mSongPlayer) {
mSongPlayer.start();
}
}
});
mSongPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
}
}
解决方法:
您需要使用MediaPlayer.OnCompletionListener在上一个曲目结束时开始新的曲目,因此您可以执行类似以下的操作(我尚未编译它,因此可能存在一些语法错误):
public void play(final Context c, ArrayList<String> songTitles) {
stop();
if (songTitles != null && songTitles.size > 0) {
final List<String> playList = new ArrayList<String>(songTitles);
String song = playList.get(0);
playList.remove(0);
mSongPlayer = MediaPlayer.create(c, getSongResourceId(song));
mSongPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp == mSongPlayer) {
mSongPlayer.start();
}
}
});
mSongPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stop();
// Recursively call the play() method with one less
// track in the list.
play(c, playList);
}
});
}
}
public int getSongResourceId(String songTitle) {
if (song.equalsIgnoreCase("shakeItOff")){
return R.raw.shaketoff;
} else if (song.equalsIgnoreCase("dropItLow")){
return R.raw.dropitlow;
} else if (song.equalsIgnoreCase("chachaslide")){
return R.raw.chachaslide;
}
}
第一次播放时,它将播放列表中的第一首曲目,然后在MediaPlayer.OnCompletionListener中,它递归地调用play()方法,并从列表中删除第一首曲目.这意味着每次调用play()时,列表都会变短,直到到达列表末尾.
标签:android-mediaplayer,audio,java,android 来源: https://codeday.me/bug/20191120/2040664.html