Media Player, stop sound before playing another

2

Good morning, I'm with a project so that when a button is pressed it performs a pre determined sound but if I press a button dps the other, the two sounds are playing, I tried for an if in case something is playing it pause and start the other
but it crashes the app when trying to check if it has nothing touching
if somebody knows a way to make 2 sounds not reproduce 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();

}
    
asked by anonymous 01.11.2015 / 21:27

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;
    }
}
    
01.11.2015 / 22:07