Android: Playing two sounds one after the other

一笑奈何 提交于 2019-12-24 08:24:04

问题


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:


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);


来源:https://stackoverflow.com/questions/14939191/android-playing-two-sounds-one-after-the-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!