Click here to Skip to main content
13,868,400 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


25 bookmarked
Posted 21 Sep 2011
Licenced CPOL

Adding Background Music to Android App

, 23 Sep 2011
Rate this:
Please Sign up or sign in to vote.
This article explains how to add background music while developing Android Apps, e.g., Games


A large chunk of Android's application development consists of Game development. Background Music is an integral part of a Game app. This article explains how to add music to any Android App using Media Player provided by Android SDK Library. Familiarity with Android activity and services is assumed here.


MediaPlayer class controls the playback of audio/video files and streams.
Its Life Cycle is implemented in the form of State Machine Diagram.The official Android development page gives a nice explanation of its Life Cycle. I would recommend that you get familiar with the life cycle of Media Player by going through it. The Media Player should be in prepared state to play the Music. In general, the media sources can be: Local resources, Internal URIs, such as one you might obtain from a Content Resolver, External URLs (streaming).
Our interest is in using local resources. So save your application's music fie in /res/raw directory.The various supported music audio files are as follows:
MP3, MIDI, WAV, MP4, MP4A, 3GP, FLAC, ADTS Raw AAC (.aac decode only).

Use a Service with MediaPlayer

In order for media to be played in the background of your app location when the user is interacting with it— you must start a Service from your application's main activity and the service shall contain all the methods related to playback. To allow activity to interact with the service, a service connection is also required. In short, we need to implement a bounded service.

Generally speaking, playback control operation may fail due to various reasons, such as unsupported audio/video format, poorly interleaved audio/video, resolution too high, streaming timeout, programming error, etc. So include sufficient error handling and recovery mechanism. Under all these error conditions, the internal player engine invokes a user supplied OnErrorListener.onError() method if an OnErrorListener has been registered beforehand via setOnErrorListener( The Media player enters in "Error" state even if no error listener has been registered.So for error handling mechanism for a media player, a good understanding of the state diagram of Media Player is a must.

Using the Code

Below is the code for a basic service implementing the media player.The code is written in JAVA by using Android SDK on Eclipse IDE. Copy this code as a separate Java file named MusicService.class in your Android application under src directory.The sample music which I played in my app is also available as download as "jingle.mp3" and should be stored in "res/raw" directory.

As this is a bound service which allows other application components to bind and interact with it, we must implement onbind() callback method. More details about the bound service is beyond the scope of this document as it primarily deals with implementation of the Media Player and a good understanding of service is assumed here.

Following are the important terms and functions implemented here and the rest are self explanatory:

  1. The service implements onErrorListener for error handling and recovery
  2. mBinder: An Ibinder object which shall be used by clients to interact with service
  3. The Constructor is empty as I am only demonstrating the background music functionality here. But depending on your application, you can perform some initialization here.
  4. Class ServiceBinder: As this service is private to the application and runs in the same process as the client, you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation or even the Service.
  5. OnCreate(): Here we create the Media player by calling mPlayer.create() and giving the path of the music file as the argument. When create is called, the media player is already in prepared state so no need to explicitly prepare the player.
    Moreover since the music has to be played non-stop, it is made to loop and setvolume is used to set the initial volume. Also the errorlistener is registered and onError() function is called when there is an error. You can write your error handling code here. In my code, on error it is stopping the player and releasing the object.
  6. OnStartCommand: Player is started here and we return START_STICKY as the music has to be played continuously throughout the app, unless paused or stopped by user.

The remaining functions are simple and self explanatory.

import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener{

    private final IBinder mBinder = new ServiceBinder();
    MediaPlayer mPlayer;
    private int length = 0;

    public MusicService() { }

    public class ServiceBinder extends Binder {
     	 MusicService getService()
    		return MusicService.this;

    public IBinder onBind(Intent arg0){return mBinder;}

    public void onCreate (){

       Player = MediaPlayer.create(this, R.raw.jingle);

       if(mPlayer!= null)

        mPlayer.setOnErrorListener(new OnErrorListener() {

	  public boolean onError(MediaPlayer mp, int what, int

			onError(mPlayer, what, extra);
			return true;

	public int onStartCommand (Intent intent, int flags, int startId)
         return START_STICKY;

	public void pauseMusic()


	public void resumeMusic()

	public void stopMusic()
		mPlayer = null;

	public void onDestroy ()
		if(mPlayer != null)
			}finally {
				mPlayer = null;

	public boolean onError(MediaPlayer mp, int what, int extra) {

		Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
		if(mPlayer != null)
			}finally {
				mPlayer = null;
		return false;

Binding the Activity to the Service

In your application's activity class (Java file), make the service connection by using the following code:

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){

	public void onServiceConnected(ComponentName name, IBinder
     binder) {
	mServ = ((MusicService.ServiceBinderbinder).getService();

	public void onServiceDisconnected(ComponentName name) {
		mServ = null;

	void doBindService(){
 		bindService(new Intent(this,MusicService.class),
		mIsBound = true;

	void doUnbindService()
      		mIsBound = false;

In the above code, I have created a service connection Scon which gets the service to be called in mServ variable in OnServiceConnected() and sets it to null once the service is disconnected. doBindService and doUnbindService are for binding and unbinding to the service respectively. There is a boolean flag mIsBound which gets set when the service is bound to activity.

Starting, Pausing, Resuming and Stopping the Music

Follow the given steps:

Step 1: First bind the service to the activity by calling doBindService on your activity's onCreate as passing an intent to the service.

Step 2: Start the service by an explicit Intent:

Intent music = new Intent();

Step 3: From your activity, wherever you want to pause, resume or stop music, call the corresponding service functions as follows:


Step 4: Don't forget to call doUnbindService from places where you want to unbind the service from the activity. An ideal place is the call to activity's onDestroy()method.

Step 5: In your application's androidmanifest file, paste the following XML code:

"service android:name="MusicService"android:enabled="true" 


  • 19th September, 2011: Initial version
  • 22nd September, 2011: Added Step 5


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

ruchira biyani
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionHow do you stop the music when pressing the home button or the app is not visible? Pin
Member 1376528710-Apr-18 13:48
memberMember 1376528710-Apr-18 13:48 
Questionit doesn't work !!!!!! Pin
SiyavashGhanbari6-Mar-15 4:30
memberSiyavashGhanbari6-Mar-15 4:30 
GeneralMy vote of 3 Pin
Franc Morales21-Apr-14 19:00
memberFranc Morales21-Apr-14 19:00 
QuestionPLease give me full source code with layout example. I tried a lot but it not work Pin
Truong Hoang Hiep21-Apr-14 9:55
memberTruong Hoang Hiep21-Apr-14 9:55 
QuestionAdding Background Music to Android game Pin
Member 1056203120-Apr-14 23:09
memberMember 1056203120-Apr-14 23:09 
AnswerRe: Adding Background Music to Android game Pin
malamute8413-Apr-15 8:53
membermalamute8413-Apr-15 8:53 
QuestionShows an syntax error in following line Pin
hirren gamit1-Dec-13 5:39
memberhirren gamit1-Dec-13 5:39 
AnswerRe: Shows an syntax error in following line Pin
Member 1065906710-Mar-14 12:29
memberMember 1065906710-Mar-14 12:29 
GeneralRe: Shows an syntax error in following line Pin
Member 1086826912-Jun-14 2:23
memberMember 1086826912-Jun-14 2:23 
Questionsir please help... Pin
carlo lagura15-Sep-13 5:47
membercarlo lagura15-Sep-13 5:47 
QuestionIt works perfectly, thank's ! Pin
Member 1022103220-Aug-13 9:32
memberMember 1022103220-Aug-13 9:32 
AnswerRe: It works perfectly, thank's ! Pin
Member 1147203223-Feb-15 18:03
memberMember 1147203223-Feb-15 18:03 
QuestionDoes not work Pin
Kavita Rege8-May-13 6:51
memberKavita Rege8-May-13 6:51 
GeneralMy vote of 3 Pin
shishir0029-Mar-13 22:42
membershishir0029-Mar-13 22:42 
QuestionI get a null pointer exception error on.... Pin
Member 977816022-Jan-13 19:54
memberMember 977816022-Jan-13 19:54 
QuestiononDestroy or STOP the music succes! Pin
biwer31-Oct-12 2:52
memberbiwer31-Oct-12 2:52 
AnswerRe: onDestroy or STOP the music succes! Pin
malamute8413-Apr-15 8:44
membermalamute8413-Apr-15 8:44 
QuestionNullPointerException Occure Pin
Sumanta12347-Oct-12 1:22
memberSumanta12347-Oct-12 1:22 
Questionpause, resume and stop not working Pin
prasiddha19862-Oct-12 10:55
memberprasiddha19862-Oct-12 10:55 
GeneralMy vote of 5 Pin
PranavJajal26-Aug-12 21:21
memberPranavJajal26-Aug-12 21:21 
QuestionCan't get to play! Pin
Member 880928010-Apr-12 19:52
memberMember 880928010-Apr-12 19:52 
AnswerRe: Can't get to play with this main activity Pin
figo86luis20005-Feb-13 23:07
memberfigo86luis20005-Feb-13 23:07 
QuestionNot Professional Pin
addoula6-Oct-11 8:45
memberaddoula6-Oct-11 8:45 
AnswerRe: Not Professional Pin
ruchira biyani6-Oct-11 9:27
memberruchira biyani6-Oct-11 9:27 
GeneralRe: Not Professional Pin
gctmadhumitha22-Oct-11 17:56
membergctmadhumitha22-Oct-11 17:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 23 Sep 2011
Article Copyright 2011 by ruchira biyani
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid