Good morning, I would like to know how I can make a code so that when I click on a button it plays a sound
Good morning, I would like to know how I can make a code so that when I click on a button it plays a sound
In the method of your button use the following code:
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
Notes:
MainActivity
in MainActivity.this
with the name of your activity sound
with R.raw.sound
with the file name of the sound you want to play. This file must be in the res\raw
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 named beep or change the'beep 'by the name of your file in the above code.
Now just call the playSound () method in your button's OnClickListener event.