Android: Mediaplayer stop / start playing raw resource

爷,独闯天下 提交于 2019-12-08 05:15:47

问题


It now plays on first press, stops on second press or press of another sound button. If I let a sound play through I can restart it or play another sound on a single press.

My goal is for the second press of the same button to stop it, but the press of a new button to just start the new sound instead of first press of new button stopping the old sound, second press starting the new sound.

I can see why it does what it does now but am not sure how to make it work the way I want.

public void playSound(int input){
    if (mp!=null && mp.isPlaying()) {
         mp.stop();
         mp.reset();
    } else{
         if (mp!=null){
             mp.reset();
             mp.release();
         }
         mp = MediaPlayer.create(Soundboard.this, input);
         mp.start();
    }
}

回答1:


This block of code:

if (mp!=null){
    mp.reset();
    mp.release();
}

will never be executed. mp can only be null at this point, as it is in the else block of an if (mp != null) test. This suggests that there is a flaw in your thinking regarding the use of this method.

If a sound has played through and you press the button, then this code will execute:

mp.release();
mp = null;

Since mp was not null, the else block doesn't execute and no new sound is played. When the button is pressed a second time, mp is now null and the else block gets executed, creating a new MediaPlayer and playing the sound.



来源:https://stackoverflow.com/questions/4812947/android-mediaplayer-stop-start-playing-raw-resource

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