Android - MediaPlayer - Example of playing sounds

Maybe you are wondering how to play a MP3 sound by clicking a simple Button on Android.

Eh, you know what? You are in the right place!

Note that this tutorial for MP3 sounds works as well with MP3 musics and of course a lot of different types of format such as WAVE or MIDI.

A complete list can be found on the official website of Android developpers:
http://developer.android.com/guide/appendix/media-formats.html.

After a presention of which MP3 we will need, we will show the source code needed for this tutorial.

MP3 files

First of all, we need .MP3 files: either created them or download them.

If you never created one, I suggest you to try a MP3 recorder such as Audacity.

But if you prefer to download them instead of created them, you have to find MP3 on Internet.

OK, we assume that we have now three MP3 files:

  1. hello.mp3
  2. goodbye.mp3
  3. what.mp3

It is important to know that if the MP3 format, of files, is not 100% valid it won't work.

Now let's check the code.

Source code

We will select the Android 2.2 (API 8) version and create a new Android project called Tuto4_BadprogTutorialPlayingSounds.

Tuto4_BadprogTutorialPlayingSoundsActivity.java

In the code below, we will "talk" with button already on the main.xml file.
So we will use an event listener on each Button to trigger the correct sound.
For that we will create a manager of sound to check which Button is clicked.
Notice that the what.mp3 file will never (normally) be played.

Location: src/package/Tuto4_BadprogTutorialPlayingSoundsActivity.java

package com.badprog.android.tutorial.mediaplayer.playingsounds;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Tuto4_BadprogTutorialPlayingSoundsActivity extends Activity {
    
    /**
     * Variables
     */
    MediaPlayer mp        = null;
    String hello         = "Hello!";
    String goodbye        = "GoodBye!";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        /**
         * Talking with the buttonHello
         */
        final Button buttonHello = (Button) findViewById(R.id.idHello);
        buttonHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                managerOfSound(hello);
            } // END onClick()
        }); // END buttonHello
        
        /**
         * Talking with the buttonGoodBye
         */
        final Button buttonGoodBye = (Button) findViewById(R.id.idGoodBye);
        buttonGoodBye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                managerOfSound(goodbye);
            } // END onClick()
        }); // END buttonGoodBye
    } // END onCreate()
    
    /**
     * Manager of Sounds
     */
    protected void managerOfSound(String theText) {
        if (mp != null) {
            mp.reset();
            mp.release();
        }
        if (theText == hello)
            mp = MediaPlayer.create(this, R.raw.hello);
        else if (theText == goodbye)
            mp = MediaPlayer.create(this, R.raw.goodbye);
        else
            mp = MediaPlayer.create(this, R.raw.what);
        mp.start();
    }
}


main.xml

Location: res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<Button
    android:id="@+id/idHello"
    android:text="@string/stringHello"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
/>    
   
<Button
    android:id="@+id/idGoodBye"
    android:text="@string/stringGoodbye"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>    

</LinearLayout>

string.xml

Location: res/values/string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, Tuto4_BadprogTutorialPlayingSoundsActivity!</string>
    <string name="app_name">Tuto 4 - PlayingSounds - BadproG.com</string>
    <string name="stringHello">Hello</string>
    <string name="stringGoodbye">Goodbye</string>

</resources>

MP3 files

We have to add a new directory named raw/ in the res/ one.

Location:

  • res/raw/goodbye.mp3
  • res/raw/hello.mp3
  • res/raw/what.mp3

Launch your app and click the Hello Button to hear the hello.mp3 file and for the GoodBye one to hear the goodbye MP3.

Great job, you made it! laugh

Comments

Comment: 

This project code very useful so thanks your sher Knowlage every one......

 

so plz help me pass one Activity but back onBackPassed(); method provious state here but ImageButton onClick event not working so any suggention that send me......

Comment: 

Thanks ..it's working fine

 

Comment: 

Good this help me :)

Thanks.

Comment: 

good example thanku very much!!!

 

Comment: 

This worked very well. Simple and effective.Thanks!!

Comment: 

I am new to the android world. I am developing an app that has 6 buttons on main screen and 5 buttons on the second screen. The 5 buttons on the main screen should be able to play the music when the user click on those buttons. And each buttons should be able to play different music that corresponds to the music that is located in the raw folder. The 6th button on the main screen should allow the user to go to the next screen (Second Screen). Likewise, the 5 buttons on the second screen should play the music that corresponds to the music in the raw folder. Please look at my code.. I don't know what is wrong with my code ?

My main Java code looks like the following...

public class MainActivity extends Activity implements OnClickListener{

public class onClickListener implements OnClickListener {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent("com.example.playaudio.SecondActivity");
startActivity(i);

}

}

public class onClick {

}

private MediaPlayer mp;
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonSwitch);
button.setOnClickListener(new onClickListener());
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Button button1=(Button)findViewById(R.id.button_1);
Button button2=(Button)findViewById(R.id.button_2);
Button button3=(Button)findViewById(R.id.button_3);
Button button4=(Button)findViewById(R.id.button_4);
Button button5=(Button)findViewById(R.id.button_5);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);

}

private void setOnClickListener(
com.example.playaudio.MainActivity.onClick onClick) {
// TODO Auto-generated method stub

}

public static void onClick(View v) {
int resId;
switch (v.getId()) {
case R.id.button_1:
resId = R.raw.a;
break;
case R.id.button_2:
resId = R.raw.b;
break;
case R.id.button_3:
resId = R.raw.c;
break;
case R.id.button_4:
resId = R.raw.d;
break;
case R.id.button_5:
resId = R.raw.e;
break;
default:
resId = R.raw.a;
break;

}

// Release any resources from previous MediaPlayer
if (mp != null) {
mp.release();

}
// Create a new MediaPlayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();

}

{
startActivity(new Intent(MainActivity.this,SecondActivity.class));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;

}

@Override

protected void onDestroy() {
if(null!=mp){
mp.release();
}
super.onDestroy();
}

Second Screen Java class

import com.example.playaudio.MainActivity.onClick;

import android.app.Activity;

import android.content.Intent;

import android.media.AudioManager;

import android.media.MediaPlayer;

import android.os.Bundle;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class SecondActivity extends Activity

{

@Override

protected void onCreate(Bundle savedInstanceState)

{

// TODO Auto-generated method stub super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

b= (Button) findViewById (R.id.buttonSwitch);

b.setOnClickListener(new onClick());

setVolumeControlStream(AudioManager.STREAM_MUSIC);

Button button7=(Button)findViewById(R.id.button7);

Button button8=(Button)findViewById(R.id.button8);

Button button9=(Button)findViewById(R.id.button9);

Button button10=(Button)findViewById(R.id.button10);

Button button11=(Button)findViewById(R.id.button11);

button7.setOnClickListener((OnClickListener) this);

button8.setOnClickListener((OnClickListener) this);

button9.setOnClickListener((OnClickListener) this);

button10.setOnClickListener((OnClickListener) this);

button11.setOnClickListener((OnClickListener) this);

}

public void onClick(View v) {

int resId;

switch (v.getId()) {

case R.id.button7:

resId = R.raw.f;

break;

case R.id.button8:

resId = R.raw.g;

break;

case R.id.button9:

resId = R.raw.h;

break;

case R.id.button10:

resId = R.raw.i;

break;

case R.id.button11:

resId = R.raw.j;

break;

default:

resId = R.raw.a;

break;

}

{

startActivity(new Intent(MainActivity.this,SecondActivity.class));

}

Please email me at xxx.

Comment: 

Hello dev,

First of all, I could suggest you copy exactly the same code I wrote.
It means each package, each file's name, etc.

Thus you'll have a good start and something that works fine.
Then after try to add and remove some code in order to do what you really want to do. smiley

 

Comment: 

Great!!!
Thank you very much!!
It's simple and good.

Comment: 

this is a very simple code for play a song. my teacher taught me a complex code compare to this.
thanks for this.

Comment: 

I have here a little function which does not need to release the sound each time AND which plays the new sound instantly. You need two member variables: m_sound (MediaPlayer) and m_actualSoundId (int)
Initialize the MediaPlayer m_sound with any sound in the onCreate function. Set the m_actualSoundId to the same R.raw.sound-id or 0. It does not matter, which sound you load on create. ;)

public void PlaySound(int soundId)
{
if(m_sound.isPlaying()) // "rewind" the sound to the start position if it was playing.
{
m_sound.pause();
m_sound.seekTo(0);
}
if(m_actualSoundID != soundId) // only create the new sound if it is another one.
{
m_sound.reset();
m_sound.release();
m_sound = MediaPlayer.create(this, soundId);
}
// finally start the sound.
m_actualSoundId = soundId;
m_sound.start();
}

use it like this: "PlaySound(R.raw.mysound);"

I hope this helps. I use it for OK and TOTAL of a cash register application. ;)

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.