Android code for playing sound in button

playing sound in android.
Producing sound in android apps.
error sound in android code.
Click sound for android button.

Before writing code for sound in android. we have to create a folder called 'raw' inside 'res' folder.
Now copy your sound file ie MP3 file to raw folder.




now open your project and start coding


step 1: Import MediaPlayer header file

import android.media.MediaPlayer;



step 2: create a variable for MediaPlayer

MediaPlayer mysound;



Step 3: Add Following code where you want to play sound

mysound=MediaPlayer.create(MainActivity.this, R.raw.click );
mysound.start();

Here Raw is folder name where you kept sound file
click is name of sound file ie MP3 file
Place this codes inside button code for producing sound after click button.


Step 4: Stop playing sound file

sound.release();

3 Comments

  1. Great and simple TY :)

    (last line is "mysound.release()" not "sound.release()" )

    ReplyDelete
  2. No way man!. It doesn't work for my android app. Some devices ignore this sound. I don't understand :(

    ReplyDelete

Add your comments here

Back to Top