MediaPlayer问题:所有歌曲同时播放



所以我尝试播放用户选择的特定歌曲组合。我正在制作一个字符串数组,这些字符串是应该在MediaPlayer中播放的文件名。问题是所有的歌曲都同时播放。我已经尝试了所有的方法,但仍然不知道如何确保播放器在开始另一首歌之前等待一首歌结束。

以下是我尝试过的:

public void play(View v){
if(player==null)
{
while(true) {
if(i==brojac) break; //checking if the arraylist has ended
if(player.isPlaying()==false) {
i++;
String s = lista.get(i).toString();
player = MediaPlayer.create(this, (this.getResources().getIdentifier(s, "raw", this.getPackageName())));
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPlayer();
}
});
player.start();
}
}
}
}
private void stopPlayer()
{
if(player!=null)
{
player.release();
player=null;
}
}

编辑

有了下面的答案,一切都正常,但玩家有明显的差距。我已经用setNextPlayer((函数解决了这个问题,但由于在播放时重新创建播放器,应用程序崩溃了。

void playSong(int currentSong) {
player = MediaPlayer.create(this, currentSong);
player1 = MediaPlayer.create(this,this.getResources().getIdentifier(lista.get(i+1).toString(),"raw",getPackageName()));
player.setNextMediaPlayer(player1);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
player.release();
i++;
if(i==brojac) return;
player1.start();
playSong(MainActivity.this.getResources().getIdentifier(lista.get(i).toString(),"raw",getPackageName()));
}
});
if(i==0) {
player.start();
}
}

我相信你想要这个:

ArrayList<Integer> songs = new ArrayList<>();
private MediaPlayer mediaPlayer;
private int currentIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Field[] fields = R.raw.class.getFields();
for (Field field : fields)
songs.add(getResources().getIdentifier(field.getName(), "raw", getPackageName()));
playSong(songs.get(currentIndex));
}

void playSong(int currentSong) {
mediaPlayer = MediaPlayer.create(this, currentSong);
mediaPlayer.setOnCompletionListener(completeListener);
mediaPlayer.start();
}
MediaPlayer.OnCompletionListener completeListener = mp -> {
mp.release();
currentIndex++;
playSong(songs.get(currentIndex));
};

说明:

下面的代码,将从raw文件夹中获取所有音频文件,并将它们存储在ArrayList中,称为歌曲:

Field[] fields = R.raw.class.getFields();
for (Field field : fields)
songs.add(getResources().getIdentifier(field.getName(), "raw", getPackageName()));

播放歌曲:

void playSong(int currentSong) {
mediaPlayer = MediaPlayer.create(this, currentSong);
mediaPlayer.setOnCompletionListener(completeListener);
mediaPlayer.start();
}

对于OnCompletionListener听众,当歌曲结束时,你需要增加currentIndex,这样songs.get(currentIndex)就会给你下一首歌曲

MediaPlayer.OnCompletionListener completeListener = mp -> {
mp.release();
currentIndex++;
playSong(songs.get(currentIndex));
};

相关内容

  • 没有找到相关文章

最新更新