问题
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