How to play audio from a specific URL using MediaPlayer in Kotlin Android
How to play audio from a specific URL using MediaPlayer in Kotlin Android.
Here's a step-by-step tutorial on how to play audio from a specific URL using MediaPlayer in Kotlin Android:
Step 1: Set up the project
- Create a new Android project in Kotlin.
- Open the "build.gradle" file (Module:app) and add the following dependency:
implementation 'androidx.media:media:1.4.1'
- Sync your project to download the dependency.
Step 2: Add the required permissions
- Open the "AndroidManifest.xml" file and add the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 3: Create the MediaPlayer instance
- Open your activity or fragment file where you want to play the audio.
- Declare a MediaPlayer variable and initialize it:
private var mediaPlayer: MediaPlayer? = null
Step 4: Prepare the MediaPlayer
- Inside the activity's
onCreate
or fragment'sonViewCreated
method, initialize the MediaPlayer object:
mediaPlayer = MediaPlayer()
- Set an
OnPreparedListener
to the MediaPlayer:
mediaPlayer?.setOnPreparedListener {
// Called when the media file is ready for playback
mediaPlayer?.start()
}
Step 5: Play audio from a URL
- Add a function to play audio from a specific URL:
private fun playAudioFromUrl(url: String) {
mediaPlayer?.reset()
try {
mediaPlayer?.setDataSource(url)
mediaPlayer?.prepareAsync()
} catch (e: IOException) {
e.printStackTrace()
}
}
- Call the
playAudioFromUrl
function with the desired URL to play audio:
val audioUrl = "http://www.example.com/audio.mp3"
playAudioFromUrl(audioUrl)
Optional Step: Handle MediaPlayer lifecycle
- Override the activity's
onPause
or fragment'sonPause
method to pause the MediaPlayer:
override fun onPause() {
super.onPause()
mediaPlayer?.pause()
}
- Override the activity's
onDestroy
or fragment'sonDestroyView
method to release the MediaPlayer:
override fun onDestroy() {
super.onDestroy()
mediaPlayer?.release()
mediaPlayer = null
}
That's it! You have learned how to play audio from a specific URL using MediaPlayer in Kotlin Android. You can now incorporate this functionality into your own applications.