How to play a sound using Mediaplayer?

Asked

Viewed 647 times

4

How can I create a button with Soundeffect using the Mediaplayer class or any other android class?

I tried using the following code I found some examples, but I was not successful.

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();
    }
}
  • You want, by clicking a button, to produce a sound?

  • yes, a sound 1 second long +-.

1 answer

3


Do so:

//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;
    }
}

In the onClick() button call the method playMusic() with the R.raw.xxx of the sound you want to play

playMusic(R.raw.song1);

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

@Override
protected void onDestroy() {
    super.onDestroy();
    releasePlayer();
}
  • Man, thank you very much, it worked perfectly. = D

Browser other questions tagged

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