Playing sound from click button!

Quickly share your Android Code Snippets here...

Playing sound from click button!

Postby JonnySnip3r » Tue Jun 16, 2009 9:57 am

Hey gus does anybody know where i can get some information about this, I want to be able to play a sound by clicking a button.

Thanks :)
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm


Postby Mr_Tremor » Thu Jul 09, 2009 10:08 pm

Please add questions to the appropriate coding problem sections. This section is for snippets of finished code.

If you want to play a sound you can do some research on the MediaPlayer class in android. You would basically just need to prepare a media player with your sound, then attach an onClick event to your button to start the playback.
Posts: 26
Joined: Tue Jun 02, 2009 6:35 pm

Re: Playing sound from click button!

Postby tonypcoyle » Tue Jul 27, 2010 10:06 pm

There is a whole section i the Dev Guide you should review (see MediaPlayer)

the basic code you need is a layout with a Button, and an activity that implements OnClickListener (to respond to the button). In the OnClick, you need the MediaPlayer code to create/play/release (for cleanup).

I created the attached as a 'stupid' one shot for my son to annoy his friends! (teenagers!) also as my own 'hello world' - new to Android & Java.

Code: Select all
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class PlayIt extends Activity implements OnClickListener {
   /** Called when the activity is first created. */
   MediaPlayer mp;
   public void onCreate(Bundle savedInstanceState) {
      ImageButton btn = (ImageButton)findViewById(;

   public void onClick(View v) {
      // TODO Auto-generated method stub
      mp = MediaPlayer.create(this, R.raw.musicfile);
      while (mp.isPlaying()) {
         // donothing
Once Poster
Once Poster
Posts: 1
Joined: Tue Jul 27, 2010 9:56 pm


Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 4 guests