Playing audio in Android

Download source code of this article.

There are more than one way to play audio and video content in Android, but the easiest way to play media content is by using MediaPlayer. MediaPlayer class encapsulate all the functionalities needed to play, seek, stream, etc. This article is about playing audio using MediaPlayer class. Video playback will be explained in another article (in near future :)).

MediaPlayer class can play all the supported audio content. It can play audio from application resource, file or from a streaming source. Playback of audio or video content is managed as a state machine. For more about the state management please refer to this link.

Following are the steps to play an audio content from an application resource:

1. Create a media player using MediaPlayer.create(context,resourceid)
2. Call MediaPlayer.prepare() method and
3. Call MediaPlayer.start() method.

Following code snippet plays an audio resource:

MediaPlayer player = MediaPlayer(this,R.raw.soundfile);

player.prepare();
player.start();

.
.
.

player.stop();
player.reset();
player.release();

player = null;

To play an audio from a file or a stream:

1. Create an instance of MdiaPlayer using new
2. Set the data source using MediaPlayer.setDataSource()
3. Call MediaPlayer.prepare();
4. Call MediaPlayer.start();

Following code snippet plays an audio file:

MediaPlayer player = new MediaPlayer();

player.setDataSource(β€œ/mnt/sdcard/media/audiofile.mp3”);
player.prepare();
player.start();

.
.
.

player.stop();
player.reset();
player.release();

player = null;

MediaPlayer is a very limited resource, so it is important to stop and release the player object once you finished playing the media, otherwise other application using the media player may not get the resource.

MediaPlayer class has different methods to manage the media playback, some of them are:

getDuration() returns the duration of the media in milliseconds.
getCurrentPosition() returns the current playback position.
isPlaying() returns true if playing is in progress otherwise false.
isLooping() returns true is looping is set otherwise false.
pause() pause the playback.
start() start or resume the playback.
seekTo() seek to the specified position.
setLooping() set looping enabled or disabled.
setVolume() set the playback volume.

MediaPlayer uses different callback interfaces to report the events, they are:

MediaPlayer.OnBufferingUpdateListener This interface is used to report the buffering progress when media is streamed from a source.

void onBufferingUpdate(MediaPlayer mp, int percent) method is called when the buffer is updated.

The first parameter mp is the MediaPlayer object and the second parameter percent is the percentage of buffering completed.

MediaPlayer.OnCompletionListener This interface is used to report the completion of the playback.

void onCompletion(MediaPlayer mp) method is called when the playback is completed.

The only parameter mp is the MediaPlayer object.

MediaPlayer.OnErrorListener This interface is used to report any error occurred while the playback is in progress.

boolean onError(MediaPlayer mp, int what, int extra) method will be called when an error occurred.

The first parameter mp is the MediaPlayer object, the second parameter what is the error occurred and the last parameter extra is the extra error information.

If you return true the playback will continue, if false is returned then playback is stopped and the OnCompletionListener will be called.

MediaPlayer.OnInfoListener This interface is used to report any warning or information has to be reported.

boolean onInfo(MediaPlayer mp, int what, int extra) method is called when a warning/info is there.

The first parameter mp is the MediaPlayer object, the second parameter what is the error occurred and the last parameter extra is the extra error information.

Return value true means the information/warning is handled, false means the information is discarded. In both the cases the playback will continue.

MediaPlayer.OnPreparedListener This interface is used to report when asynchronous method prepareAsync() is used to prepare the MediaPlayer.

void onPrepared(MediaPlayer mp) method is called when the prepare is completed.

The only parameter mp is the MediaPlayer object.

MediaPlayer.OnSeekCompleteListener This interface is used to report the completion of the seek operation.

void onSeekComplete(MediaPlayer mp) method will be called when the seek operation is completed.

The only parameter mp is the MediaPlayer object.

MediaPlayer.OnVideoSizeChangedListener This interface is used to report the a change in size of video playback. This is not called in case of audio playback.

void onVideoSizeChanged(MediaPlayer mp, int width, int height) method is called once the size is changed.

The first parameter mp is the MediaPlayer object, second parameter width is the new width and the third parameter height is the new height.

Sample application of this article lists all the audio files in the external storage media. To enumerate the audio files I used the MediaStore.Audio.Media.EXTERNAL_CONTENT_URI content URI. This returns the cursor containing all the supported audio files in the external storage media. When an item is clicked, the application start playing the particular audio file. To show the current playback position I used a Handler class. and a Runnable command that will be fired every second to update the current playback position. We could use the default MediaController for this purpose but practically I faced a problem of not updating seek bar continuously. I haven’t figured it out why it is not updating. A screenshot of the application is shown below:

device

Hope this article is helpful for you.

Happy coding! πŸ™‚

7 Comments

Add yours →

  1. It’s wonderfull, help me very much !!! thanks a lot

  2. will this work in android version 1.6 or above. I am trying to stream a shoutcast internet radio station, and I am told that streaming support was not added until andoid version 2.2.

  3. Hi,
    I tried you code for music player but it does not work , Can you tell me where i put my video file to work this code.
    Thanks in advance πŸ™‚

  4. How can i get this to show a list from the res/raw folder and then when you click on an item it plays?

  5. Nice music player works great…how can i get it to show a list from the res/raw folder of my mp3’s so i can play those files?

  6. Hi Krishnaraj Varma,you don’ t initializate in drawable . why Imagebutton can use android: src”@drawable/ic_media_play”

Leave a Reply