Media Player, stop sound before playing another

Asked

Viewed 467 times

2

Good morning, I’m with a project so that when a button is pressed it will perform a predetermined sound
however if I press a dps button on the other, it gets both sounds ringing, I tried to if in case something is playing it pause and get the other
however it crashes the app while trying to check if there is nothing touching
if anyone knows a way to make 2 sounds not play at the same time I am very grateful :D

    public void nelson (View view) {
    mp = MediaPlayer.create(this, R.raw.nelson);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.release();
                mp = null;
            }
        });
        mp.start();

}
  • Post the code of the two buttons, it will be easier to give an answer.

  • ready put

1 answer

2


Before creating a Mediaplayer destroy the previous one, if any.

//Use sempre a mesma variável para guardar o objecto MediaPlayer
private MediaPlayer mp = null;

public void nelson (View view) {

    //Destrói o MediaPlayer caso haja algum criado.
    releasePlayer();
    mp = MediaPlayer.create(this, R.raw.nelson);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {

                //Destrói o MediaPlayer
                releasePlayer();
            }
        });
        mp.start();

}

private void releasePlayer() {
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.