Adding Background Music to Android App

  • Published on

  • View

  • Download

Embed Size (px)


add background music to android app


Adding Background Music to Android Appruchira biyani,23 Sep 2011 This article explains how to add background music while developing Android Apps, e.g., GamesIntroductionA 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.BackgroundMediaPlayerclass 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 (.aacdecode only).Use a Service with MediaPlayerIn 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 suppliedOnErrorListener.onError()method if anOnErrorListenerhas been registered beforehand viasetOnErrorListener( 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 CodeBelow 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 namedMusicService.classin your Android application undersrcdirectory.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 implementonbind()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 implementsonErrorListenerfor error handling and recovery2. mBinder: AnIbinderobject which shall be used by clients to interact with service3. 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 theBinderclass and returning an instance of it fromonBind(). The client receives theBinderand can use it to directly accesspublicmethods available in either theBinderimplementation or even theService.5. OnCreate(): Here we create the Media player by callingmPlayer.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 theerrorlisteneris registered andonError()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 returnSTART_STICKYas the music has to be played continuously throughout the app, unless paused or stopped by user.The remaining functions are simple and self explanatory.Collapse|Copy Codeimport;import android.content.Intent;import;import;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; } }

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

@Override public void onCreate (){ super.onCreate();

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

if(mPlayer!= null) { mPlayer.setLooping(true); mPlayer.setVolume(100,100); }

mPlayer.setOnErrorListener(new OnErrorListener() {

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

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

@Overridepublic int onStartCommand (Intent intent, int flags, int startId){ mPlayer.start(); return START_STICKY;}

public void pauseMusic(){if(mPlayer.isPlaying()){mPlayer.pause();length=mPlayer.getCurrentPosition();


public void resumeMusic(){if(mPlayer.isPlaying()==false){mPlayer.seekTo(length);mPlayer.start();}}

public void stopMusic(){mPlayer.stop();mPlayer.release();mPlayer = null;}

@Overridepublic void onDestroy (){super.onDestroy();if(mPlayer != null){try{ mPlayer.stop(); mPlayer.release();}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){try{mPlayer.stop();mPlayer.release();}finally {mPlayer = null;}}return false;}Binding the Activity to the ServiceIn your application's activity class (Java file), make the service connection by using the following code:Collapse|Copy Codeprivate boolean mIsBound = false;private MusicService mServ;private ServiceConnection Scon =new ServiceConnection(){

public void onServiceConnected(ComponentName name, IBinder service) {mServ = ((MusicService.ServiceBinder)service).getService();}

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

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

void doUnbindService(){if(mIsBound){unbindService(Scon); mIsBound = false;}}In the above code, I have created a service connectionSconwhich gets the service to be called inmServvariable inOnServiceConnected()and sets it tonullonce the service is disconnected.doBindServiceanddoUnbindServiceare for binding and unbinding to the service respectively. There is a boolean flagmIsBoundwhich gets set when the service is bound to activity.Starting, Pausing, Resuming and Stopping the MusicFollow the given steps:Step 1: First bind the service to the activity by callingdoBindServiceon your activity'sonCreateas passing an intent to the service.Step 2: Start the service by an explicitIntent:Collapse|Copy CodeIntent music = new Intent();music.setClass(this,MusicService.class);startService(music);Step 3: From your activity, wherever you want to pause, resume or stop music, call the corresponding service functions as follows:Collapse|Copy CodemServ.pauseMusic();mServ.resumeMusic();mServ.stopMusic();Step 4: Don't forget to calldoUnbindServiceand stopService(new Intent(MainActivity.this, MusicService.class)) from places where you want to unbind the service from the activity and stop the service. An ideal place is the call to activity'sonDestroy()method.Step 5: In your application'sandroidmanifestfile, paste the following XML code:Collapse|Copy Code"service android:name="MusicService"android:enabled="true" History 19thSeptember, 2011: Initial version 22ndSeptember, 2011: AddedStep 5


View more >