Monday, September 2, 2013

Play sound in android example

You can play sound file in your android application.You need MP3 file which you want to play.
Here is full description and only one method you need to apply in your code.


  • First create folder in res named raw.Copy MP3 file in it (in raw folder).
  • Generate MediaPlayer Object in Activity class.Make the changes as shown in BOLD.


                                    public class MainActivity extends Activity {

                                 MediaPlayer mp;
                                    @Override
                                public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                       setContentView(R.layout.activity_main);
                          
}
                                     }


  • Create one method playSound() in your activity class and add following code:

               
 
                 private void playSound() {
mp = MediaPlayer.create(MultiActivity.this, R.raw.sound_file);
        mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}


  • Add setOnClickListener() method of button and only call this playSound() method.
            
                 playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
playSound();
}
});


  • For Big MP3 file you can create one button to stop sound.Just put mp.release(); and mp.stop(); code in it.
      •  

No comments:

Post a Comment