How to play MediaPlayer in Android Studio?
MediaPlayer is a class in Android that provides various features for playing audio and video files and streams in apps. It supports playing of common media formats like mp3, mp4, wav etc. With MediaPlayer you can control audio/video playback, pause/resume, fast forward, rewind and more. It also provides handy callbacks for monitoring events during playback.
In summary, MediaPlayer (reference) offers a powerful and easy to use API for working with media playback in Android apps. This guide will cover the basics of setting up and using MediaPlayer to play audio/video in Android Studio.
Add MediaPlayer Dependencies
To use MediaPlayer in your Android app, you need to add the necessary dependencies in your app’s build.gradle file. This allows Gradle to download the required libraries when building your project.
Add the following dependency in your module’s build.gradle file:
implementation 'com.google.android.exoplayer:exoplayer:2.X.X'
Replace ‘2.X.X’ with the latest stable version of the ExoPlayer library. Check the Media2 release notes for the current version.
This dependency provides access to the MediaPlayer class and related media playback capabilities. Make sure to sync your project after adding this so the library is downloaded.
In addition to this dependency, you may also need to add the following permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
With the dependency and permissions added, you can now start using MediaPlayer in your app.
Create a Media Player Object
To play media files in Android, we need to instantiate a MediaPlayer object. The MediaPlayer class provides APIs for controlling playback of audio/video files and streams. Here’s how to instantiate a MediaPlayer object:
First, create a new instance of the MediaPlayer class:
MediaPlayer mediaPlayer = new MediaPlayer();
This creates a media player object that we can use to control media playback. According to the Android developer documentation, the MediaPlayer class must be instantiated on the main thread.
Now we have a MediaPlayer instance that can be used to play audio or video files in our Android app.
Set Media Source
To set the media source in Android, use the setDataSource()
method on the MediaPlayer
object. This transfers the MediaPlayer
from the Idle state to the Initialized state. The source can be set from different locations:
- From a file path –
setDataSource(String path)
. For example:
mediaPlayer.setDataSource("/sdcard/music.mp3")
- From a URI –
setDataSource(Context context, Uri uri)
. For example:
mediaPlayer.setDataSource(context, Uri.parse("content://media/external/audio/media/16"))
- From a file descriptor –
setDataSource(FileDescriptor fd)
. For example:
mediaPlayer.setDataSource(getAssets().openFd("music.mp3"))
Note that for setting from a file path, use a fully qualified absolute path. Relative paths and “file://” urls may not work on Android 10 and above due to security changes.
It’s recommended to set the data source in a try-catch block to handle any errors:
try {
mediaPlayer.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
Once the data source is set, the MediaPlayer
needs to be prepared before starting playback.
Prepare MediaPlayer
After creating a MediaPlayer object, the next step is to prepare it to play the media file. This is done by calling the prepare()
method on the MediaPlayer object.
According to the Android documentation, calling prepare()
prepares the player for playback, synchronously. After setting the datasource and the display surface, you need to either call prepare()
or prepareAsync()
.
The prepare()
method allocates resources for playback, such as audio/video decoders. This call is synchronous and blocks until completion. After prepare()
returns successfully, the MediaPlayer object is ready to start when start()
is called.
Here is an example of preparing a MediaPlayer object:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare(); // prepare synchronously
// Now mediaPlayer is prepared and ready for playback
Calling prepare()
method is a key step to getting the MediaPlayer ready for playback. The next step will be to start actual playback.
Start Playback
To begin playback of media in the MediaPlayer, call the start()
method. This method will start playing the media source that was set with setDataSource()
or setAudioStream()
. For example:
mediaPlayer.start();
The start()
method will begin playback from the current position. If playback has not been prepared with prepare()
or prepareAsync()
, it will first call prepare()
before starting.
As noted in the Android developer reference, the start()
method can throw an IllegalStateException if called before prepare()
or after release()
. So it’s important to have prepared the MediaPlayer first.
Once started, the MediaPlayer will run asynchronously and send updates on playback completion or errors via listeners. Be sure to implement the appropriate listeners to handle these events.
Pause and Resume
To pause playback in Android MediaPlayer, call the pause() method on the MediaPlayer object. This will pause the audio/video playback and put the MediaPlayer into a paused state. For example:
myMediaPlayer.pause();
To resume playback from the paused state, call the start() method on the MediaPlayer object. This will resume playback from where it was paused. For example:
myMediaPlayer.start();
According to the Android documentation, when pause() is called, the MediaPlayer enters the paused state. The transition from playing to paused happens asynchronously, so the paused state may not happen immediately. It’s important to wait for the paused state before calling start() to resume.
One common issue is that pause/resume stops working after some time. This is a known Android bug that can happen after repeated pause/resume calls. A workaround is to call prepare() again before calling start() to resume playback.
Stop Playback
To stop media playback at any time, call the stop() method on the MediaPlayer object. For example:
mediaPlayer.stop();
This will stop the playback immediately and reset the MediaPlayer object to its uninitialized state. Once stopped, playback cannot be resumed from the current position – the entire media source needs to be prepared again before playing it.
Stopping playback completely releases resources like the audio session and surface used by the MediaPlayer. This allows other applications to seamlessly begin playback once your application is done.
It’s important to always call stop() when you are finished playing media, to ensure resources are properly cleaned up.
According to the Android developer documentation, calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Reset MediaPlayer
To reset the MediaPlayer
to its uninitialized state, use the reset()
method. This method clears any audio/video data and resources associated with the media player and restores it to an idle state. Here is an example usage from the Android Developers reference:
mediaPlayer.reset();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
Calling reset()
releases resources and puts the MediaPlayer
back into an unprepared state. This is useful when you want to reuse the same MediaPlayer
instance to play different media files. The alternative is calling release()
and creating a new MediaPlayer
instance each time.
Some key points about using reset()
:
- It clears any existing media and data loaded in the player.
- The player returns to the
Idle
state. - You must call
setDataSource()
andprepare()
again before playback. - It’s more efficient than releasing and re-creating the
MediaPlayer
.
Overall, reset()
provides a convenient way to reuse an existing MediaPlayer
to play new media files while retaining its initialized state.
Release Resources
It is important to release the resources used by the MediaPlayer when you are done with it. The MediaPlayer uses resources like audio decoders and graphic buffers that need to be released so they can be used elsewhere in the system. To release the resources, call the release() method:
For example:
mediaPlayer.release();
Calling release() will free all the resources and release the audio decoders and buffers held by the MediaPlayer. Once release() is called, the MediaPlayer object can no longer be used and should be recreated if needed again.
According to the Android developer documentation, the resources will also automatically be released when the MediaPlayer object is garbage collected. However, it is better to manually release resources by calling release() rather than relying on garbage collection.