How to play sound on android

Asked

Viewed 5,551 times

2

Good morning, I would like to know how I can make a code so that by clicking a button it plays a sound

2 answers

4


In your button method 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:

  • Substitute MainActivityin MainActivity.this by the name of his Activity
  • Substitute sound in R.raw.sound by the name of the sound file you want to play. That file has to be in the folder res\raw

1

Crie a pasta raw como mostra a imagem..

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 your button’s Onclicklistener event.

Browser other questions tagged

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