How to call a sound when clicking the android button

Asked

Viewed 2,456 times

1

Hello, would you like to know how to call a more efficient sound? 'Cause I’m using this method :

Button button1;
MediaPlyer mp;
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {


    mp = MediaPlayer.create(Teste.this, R.raw.som);
    mp.start();

    }

});

and I’m in trouble because it works, when you click several times there are times that the sound doesn’t come out anymore.

2 answers

1


I ran some tests here and found that mistake (error (-19,0)) happens when you create several instances of MediaPlayer and does not call release() in none of them.

Add this after MediaPlayer.create(...):

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        if(mp != null) {
            mp.release();
            mp = null;
        }
    }
});

The above example releases the MediaPlayer right after you finish playing the sound.

The ideal would be for you to initialize this MediaPlayer only once (in your OnCreate, for example) and reuse the same instance until you no longer need to.

  • this error is appearing The method killMediaPlayer() is undefined for the type MediaPlayer and

  • @Rodolfo Take a look at my updated response.

0

Primeiro crie a pasta raw como na imagem abaixo

Then add this code:

private void playSound() {
   MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.beep);
   mediaPlayer.start();
}

I put your audio in the raw folder with the name beep or change the beep by the name of your file in the above code.

Now just call the method playSound() at the event Onclicklistener of your button.

Browser other questions tagged

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