Professional Documents
Culture Documents
Introduction
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.
Background
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).
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(android.media.MediaPlayer.OnErrorListener) . 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.
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
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;
}
});
}
@Override
public 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;
}
@Override
public 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;
}
mIsBound = true;
}
void doUnbindService()
{
if(mIsBound)
{
unbindService(Scon);
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 anddoUnbindService are for binding and unbinding to the service respectively.
There is a boolean flag mIsBoundwhich gets set when the service is bound to activity.
Step 3: From your activity, wherever you want to pause, resume or stop music, call the corresponding service
functions as follows:
Collapse | Copy Code
mServ.pauseMusic();
mServ.resumeMusic();
mServ.stopMusic();
doUnbindService and
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's onDestroy()method.
Step 5: In your application's androidmanifest file, paste the following XML code:
Collapse | Copy Code
"service android:name="MusicService"android:enabled="true"
History