How to play a sound using Mediaplayer?

4

How can I create a button with SoundEffect using the MediaPlayer class or any other android class?

I tried using the following code that I found some examples, but I did not succeed.

public void playMusic(){
    if(player == null){
        try {
            player = MediaPlayer.create(TelaJogoSingle.this, R.raw.song1);
            player.start();
        }
        catch (IllegalArgumentException e) { e.printStackTrace(); }
        catch (SecurityException e) { e.printStackTrace(); }
        catch (IllegalStateException e) { e.printStackTrace(); }

    }else{
        player.start();
    }
}
    
asked by anonymous 09.11.2015 / 22:45

1 answer

3

Do this:

//Declare uma variável de instância para o player
private MediaPlayer mp = null;

//Escreva um método para tocar o som
public void playMusic(int songId) {

    //Se algum som ainda estiver a tocar pára-o
    releasePlayer();

    mp = MediaPlayer.create(TelaJogoSingle.this, songId);
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            //No final de tocar liberta o media player para poder ser novamente utilizado
            releasePlayer();
        }
    });

    //Toca o som
    mp.start();

}

//Método para libertar o media player
private void releasePlayer() {
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
}

No onClick() button calls method playMusic() with R.raw.xxx of sound you want to play

playMusic(R.raw.song1);

In method onDestroy() ensure that the player is released / destroyed:

@Override
protected void onDestroy() {
    super.onDestroy();
    releasePlayer();
}
    
09.11.2015 / 22:58