Android: Playing two sounds one after the other

2019-09-06 17:42发布

I am trying to play two sound items, one after the other

MediaPlayer mp        = null;

 protected void produceErrorSound(int index) {
        if (mp != null) {
            mp.reset();
            mp.release();
        }


        mp = MediaPlayer.create(this, index);

        mp.start();
    }


public void correctAnswerAndNext(){
    produceErrorSound(R.raw.right1) ;
    produceErrorSound(R.raw.right1) ;
}

but only second sound is produced. is there any alternative approach?

1条回答
再贱就再见
2楼-- · 2019-09-06 18:02

I can't see any wait mechanism in your code.

You can use an onCompletionListener to receive a callback when your first MediaPlayer has finished playback. At that point you can start the second MediaPlayer.

An alternative way in Jellybean (and later versions) is to use the audio chaining functionality (i.e. setNextMediaPlayer) to automatically start another MediaPlayer as soon as the current one has finished playing. Something like this (I've omitted the calls to setDataSource etc for brevity):

mediaPlayer1.prepare();
mediaPlayer2.prepare();   
mediaPlayer1.start();
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
查看更多
登录 后发表回答