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 :)
JonnySnip3r
Developer
Developer
 
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm

Top

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.
Mr_Tremor
Developer
Developer
 
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.app.Activity;
import android.media.MediaPlayer;
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;
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
       
      ImageButton btn = (ImageButton)findViewById(R.id.PlayItButton);
      btn.setOnClickListener(this);
       
   }

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

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 8 guests