Skip to main content

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

  1. Create a new Android project in Kotlin.
  2. Open the "build.gradle" file (Module:app) and add the following dependency:
implementation 'androidx.media:media:1.4.1'
  1. Sync your project to download the dependency.

Step 2: Add the required permissions

  1. 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

  1. Open your activity or fragment file where you want to play the audio.
  2. Declare a MediaPlayer variable and initialize it:
private var mediaPlayer: MediaPlayer? = null

Step 4: Prepare the MediaPlayer

  1. Inside the activity's onCreate or fragment's onViewCreated method, initialize the MediaPlayer object:
mediaPlayer = MediaPlayer()
  1. 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

  1. 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()
}
}
  1. 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

  1. Override the activity's onPause or fragment's onPause method to pause the MediaPlayer:
override fun onPause() {
super.onPause()
mediaPlayer?.pause()
}
  1. Override the activity's onDestroy or fragment's onDestroyView 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.