How to play sound in android [duplicate]

2

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

    
asked by anonymous 23.10.2015 / 17:12

2 answers

4

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:

  • Replace MainActivity in MainActivity.this with the name of your activity
  • Replace sound with R.raw.sound with the file name of the sound you want to play. This file must be in the res\raw
23.10.2015 / 17:19
1

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.

    
27.04.2017 / 05:34