How to call a sound when you click the android button [duplicate]

1

Hello, I would like to know how to call a more efficient sound? 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, clicking several times has the time that the sound does not come out any more.

    
asked by anonymous 29.01.2015 / 18:27

2 answers

1

I did some tests here and discovered that this error (-19,0) happens when you create multiple instances of MediaPlayer and do not call release() on any 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 example above releases MediaPlayer soon after you finish playing the sound.

Ideally, you should initialize this MediaPlayer only once (in your OnCreate , for example) and reuse the same instance until you no longer need it.

    
29.01.2015 / 18:46
0

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 code above.

Now you just call the playSound () method in the OnClickListener event of your button.

    
27.04.2017 / 05:36