playSound method to play MP3 on Android

This is an example to implement a method to play an MP3 file (in the asset folder) programmatically in Android development.

Create a new Android application project in the Eclipse (with ADT).

Copy the sound files into the asset folder of the project. We have the mp3 files named “1.mp3”, “2.mp3” and “3.mp3” respectively.


Create the UI to hold all the buttons to play the files respectively.


Copy and paste the method below in the Main Activity, and call the method by sending the MP3 file name as the argument.

public void playSound(String soundName){
Boolean mpPlayingStatus=false;
//mp=new MediaPlayer();

try{//try to check MediaPlayer status
catch (Exception e){
//if the MediaPlayer is playing a sound, stop it to play new sound
if (mpPlayingStatus==true){
mp.stop(); //stop the sound
mp.release(); //remove sound from the memory
mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets().openFd(soundName);
//set the sound source file

mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare(); // prepare for playback
mp.start(); //play the sound
afd.close();//release the file descriptor

}//try block
catch(IOException e) {
//display the error message in debug
Log.i("Error playing sound: ", e.toString());
}//end playSound

Get the complete source here –>

No comments:

Post a Comment

Popular Posts