Android’s MediaPlayer 🔊

ibrahimcanerdogan
4 min readApr 13, 2024

--

Photo by Volodymyr Hryshchenko on Unsplash

In the realm of Android development, media playback is a crucial aspect, whether it’s for audio or video content. Android provides developers with robust tools to implement media playback seamlessly into their applications. One such tool is the Media Player, a versatile API that facilitates the retrieval, decoding, and playback of both audio and video with minimal setup. In this guide, we’ll delve into the nuances of utilizing the Android Media Player effectively for various playback scenarios.

🟢 ANDROID WITH MACHINE LEARNING! (COURSE)

🟢 KOTLIN INTERVIEW BOOTCAMP! (COURSE)

The Android Media Player is an essential component for playing audio and video content within Android applications. It serves as the primary API for handling media playback tasks. With its intuitive interface, developers can effortlessly integrate audio and video playback functionalities into their apps with minimal boilerplate code.

Playing Media from Local Resources

One of the fundamental ways to utilize the Media Player is by playing media files stored locally within the app’s resources. Developers can achieve this by creating a Media Player instance and specifying the resource file’s identifier. Let’s illustrate this with Kotlin code:

val mediaPlayer = MediaPlayer.create(context, R.raw.audio_file)
mediaPlayer.start()

Playback Using URI

Android also allows playback of media files using Uniform Resource Identifiers (URIs). This method enables developers to play media from various sources, including local files and online streams. Here’s how you can play media using a URI:

val uri = Uri.parse("android.resource://${packageName}/${R.raw.audio_file}")

MediaPlayer().apply {
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
setDataSource(context, uri)
prepare()
start()
}

Streaming Media from Online Sources

For streaming media content from online sources, developers can utilize the Media Player by specifying the URL of the media resource. This approach enables seamless playback of online audio and video streams. Here’s a snippet demonstrating playback from a URL:

val url = "http://example.com/audio.mp3"
val mediaPlayer = MediaPlayer()
mediaPlayer.setDataSource(url)
mediaPlayer.prepare()
mediaPlayer.start()

OR

val url = "http://example.com/audio.mp3"

MediaPlayer().apply {
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
setDataSource(url)
prepare()
start()
}

Background Media Playback

Android applications often require the ability to play media in the background, even when the app is not in the foreground. This can be achieved by leveraging Android Services. Here’s how you can implement background media playback using a Service:

// Defines a constant ACTION_PLAY representing the action to start playing audio. This action will be used to trigger the playback functionality in the service.
const val ACTION_PLAY = "com.example.action.PLAY"

class MyService : Service(), MediaPlayer.OnPreparedListener {

companion object {
private val TAG = MyService::class.java.simpleName
}

private var mMediaPlayer: MediaPlayer? = null

// Overrides the onBind method, indicating that this service does not provide binding capabilities.
override fun onBind(intent: Intent?): IBinder? {
return null
}

// Implements the onPrepared method of MediaPlayer.OnPreparedListener, which is called when the media player is prepared for playback. It starts the playback of the media.
override fun onPrepared(mp: MediaPlayer) {
mp.start()
}

// Overrides the onStartCommand method, which is called when the service is started. It receives an Intent containing the action to perform. If the action is ACTION_PLAY, it initiates the audio playback logic.
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val action: String? = intent.action

when(action) {
ACTION_PLAY -> {
// Within the ACTION_PLAY block, it creates a Uri for the audio file stored in the application's resources. Then, it initializes the MediaPlayer, sets the audio attributes, sets the data source using the Uri, prepares the media player asynchronously, and starts the playback.
val audioUri = Uri.parse(
"android.resource://" +
packageName +
"/" +
R.raw.audio_file
)
mMediaPlayer = MediaPlayer()
mMediaPlayer?.apply {
setOnPreparedListener(this@MyService)
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
setDataSource(this@MyService, audioUri)
prepareAsync()
start()
}
}
}
return START_STICKY
}

// Overrides the onDestroy method, which is called when the service is destroyed. It releases the MediaPlayer resources to free up system resources.
override fun onDestroy() {
super.onDestroy()
mMediaPlayer?.release()
}

}

Let’s not forget to add the service to the “application” tag in AndroidManifest.xml!

<service android:name=".MyService"/>

Play Background Audio

val intent = Intent(this, MyService::class.java)
intent.action = ACTION_PLAY
startService(intent)

Play Stop Audio

val intent = Intent(this, MyService::class.java)
intent.action = ACTION_PLAY
stopService(intent)

Conclusion

Mastering media playback in Android is essential for creating engaging and feature-rich applications. With the Android Media Player API and supporting components like Services, developers have powerful tools at their disposal to deliver seamless media experiences to users. By understanding the intricacies of media playback and leveraging the capabilities of the Media Player, developers can create compelling applications that captivate and delight users.

In conclusion, this guide has provided a comprehensive overview of utilizing the Android Media Player for various media playback scenarios, empowering developers to create immersive and dynamic multimedia experiences within their Android applications.

İbrahim Can Erdoğan

LINKEDIN

YOUTUBE

UDEMY

GITHUB

--

--

ibrahimcanerdogan
ibrahimcanerdogan

Written by ibrahimcanerdogan

Hi, My name is Ibrahim, I am developing ebebek android app within Ebebek. I publish various articles in the field of programming and self-improvement.

No responses yet