How audio files can be play through MediaPlayer in Android?


The MediaPlayer class in Android allows applications to play audio and video files. It supports playback of various media file formats like MP3, AAC, OGG, WAV, and MPEG-4. This tutorial focuses specifically on using MediaPlayer to play audio files in Android applications.

The goal is to provide a step-by-step guide on how to use the MediaPlayer API to set up audio playback in an Android app. We will cover preparing the audio file, configuring MediaPlayer properties, playing, pausing and stopping the audio, properly releasing resources, and handling errors. Code snippets will demonstrate implementation. After reading, you should have a good understanding of audio playback using MediaPlayer on Android.

Setting up MediaPlayer

To use the MediaPlayer class in Android, the first step is to import the MediaPlayer class:


Next, create and initialize a MediaPlayer object. This is typically done in the onCreate() method:

MediaPlayer mediaPlayer = new MediaPlayer();

Then set the data source for the audio file. This can be done by setting the MediaPlayer data source to a Uri representing the file location:[1]

mediaPlayer.setDataSource(getApplicationContext(), audioFileUri);

The Uri can represent files stored on the device’s external storage, downloaded from the internet, or loaded as app assets. This initializes the MediaPlayer object to play the specified audio file.

Preparing the audio file

Android supports audio playback for a variety of popular formats like MP3, AAC, OGG, MIDI, WAV, and more. The full list of supported formats can be found in the Android documentation at

For playback in your Android app, audio files should be stored in the /res/raw folder of your project. This allows you to easily access them using the Resource APIs. The raw folder contains resources that are not compiled into resources like drawables, layouts, etc. So storing raw audio files here keeps them bundled with the app while maintaining the original file format.

If you need to play audio in a format not natively supported by Android, you may need to convert it first before adding to the res/raw folder. There are many converter tools and libraries available to handle this conversion programmatically if needed.

Setting MediaPlayer Properties

There are several key properties of the MediaPlayer that can be set to configure audio playback behavior in your Android app:

Setting Audio Stream Type

The audio stream type determines how the audio will be played back on the device. The most common values are STREAM_MUSIC for music playback, STREAM_NOTIFICATION for notifications, and STREAM_ALARM for alarm sounds.

For basic media playback, STREAM_MUSIC is usually the best choice. You can set it like this:


For more advanced control over audio routing between speaker, earpiece, and headphones, you may need to experiment with the other stream types as discussed in this Stack Overflow post.

Enabling Looping

To make the media file loop continuously, set the looping property to true:


This will restart playback from the beginning after reaching the end of the file.

Setting Volume

The volume can be set on a linear scale from 0 (mute) to 1.0 (full volume) like so:

mediaPlayer.setVolume(0.5f, 0.5f); // left and right volume

Make sure to properly handle the user’s device volume controls as well for a good user experience.

Playing the Audio

To start audio playback, call the start() method on the MediaPlayer instance. This will begin playing the audio from the current position. For example:


To be notified when the playback completes, you can set an OnCompletionListener on the MediaPlayer. This listener will be called when the end of the audio file is reached during playback. For example:

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  public void onCompletion(MediaPlayer mp) {
    // Handle completion here   

Inside the onCompletion() callback, you can take actions like stopping the MediaPlayer, releasing resources, or loading a new audio file to play next.

Pausing and resuming

To pause audio playback in Android, you can call the pause() method on the MediaPlayer instance. This will pause the audio at the current playback position. For example:


To resume playback from the paused position, you can call the start() method:


This will resume playback from where it was paused. According to the Android documentation, calling start() after pause() is the correct way to resume playback.

The pause() and start() methods allow fine grained control over the playback state. You can pause when needed, and resume playback when ready. This is useful for implementing playback controls like play/pause buttons.

Stopping playback

To stop the audio playback at any time, you can call the stop() method on the MediaPlayer instance according to the MediaPlayer documentation. This will stop the playback and reset the MediaPlayer to its uninitialized state.

For example:

MediaPlayer mediaPlayer = new MediaPlayer(); 


Calling stop() essentially resets the MediaPlayer by releasing all resources like the audio source, wakelock and hardware acceleration. This stops the playback immediately. It also sets the MediaPlayer object back to its idle state so it can be prepared again for another audio file if needed.

It is important to stop the MediaPlayer when you are done with audio playback. Allowing the MediaPlayer to run unnecessarily can use up device resources. Calling stop() and resetting the MediaPlayer is good practice when audio playback completes.

Releasing resources

It is important to properly release the MediaPlayer resource when it is no longer needed. This is done by calling the mediaPlayer.release() method.

The release() method should be called as soon as the MediaPlayer is no longer needed, such as when the activity or fragment using it is destroyed. Failing to release the MediaPlayer can lead to memory leaks and wasted resources.

According to the Android documentation, the general rule is to release the MediaPlayer instance when it is no longer in use, typically in the onDestroy() method of an Activity or Fragment. Some examples recommend releasing it in onPause() as well.

For example:

public void onDestroy() {
  if (mediaPlayer != null) {
    mediaPlayer = null; 

Releasing the MediaPlayer this way helps ensure resources like audio focus are properly cleaned up.

Handling errors

MediaPlayer operations can fail and throw exceptions, so it’s important to handle errors properly. Some common exceptions to watch for include:

MediaPlayer.OnErrorListener – This listens for errors during playback and other operations.

IllegalStateException – Thrown when calling a method at an inappropriate time, such as calling prepare() twice or calling start() before prepare().

IOException – Occurs if the audio file can’t be opened due to an I/O error.

To handle errors:

  • Wrap code in try/catch blocks and handle exceptions appropriately.
  • Implement MediaPlayer.OnErrorListener to catch errors.
  • Check method documentation to avoid calling methods at the wrong times.
  • Verify audio files exist before attempting playback.
  • Log exceptions to help debug issues.

Careful error handling ensures robust media playback and improves the user experience.

Example code

A good example for implementing audio playback in an Android app is the Universal Android Music Player sample from the official Android project. This app demonstrates playing audio files stored locally or over the network.

Some key steps in the code:

  • Create a MediaPlayer instance
  • Set the data source to a URI for the audio file
  • Call prepare() to load the media resource
  • Set listeners for playback events
  • Call start() to begin playback
  • Call pause()/resume() to pause and resume
  • Call release() when done to free resources

The app handles both local audio files as well as streaming audio. It demonstrates best practices like properly releasing the MediaPlayer and handling errors gracefully. Reviewing the source of this sample app is a great way to learn how to correctly implement audio playback in an Android application.

Leave a Reply

Your email address will not be published. Required fields are marked *