Skip to main content

How to implement audio streaming using MediaPlayer in Kotlin Android

How to implement audio streaming using MediaPlayer in Kotlin Android.

Here is a step-by-step tutorial on how to implement audio streaming using MediaPlayer in Kotlin Android.

Step 1: Set up the project

  • Create a new Android project in Android Studio.
  • Open the build.gradle file (app level) and add the following dependency:
implementation 'androidx.appcompat:appcompat:1.3.0'

Step 2: Add the necessary 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: Design the layout

  • Open the activity_main.xml file and add a Button and a ProgressBar to control the audio playback and display the loading progress respectively. For example:
<Button
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />

<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Step 4: Write code to handle audio streaming

  • Open the MainActivity.kt file and declare the necessary variables:
import android.media.MediaPlayer
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ProgressBar

class MainActivity : AppCompatActivity() {
private lateinit var mediaPlayer: MediaPlayer
private lateinit var btnPlay: Button
private lateinit var progressBar: ProgressBar

private val audioUrl = "https://example.com/audio.mp3" // Replace with your audio URL

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

mediaPlayer = MediaPlayer()
btnPlay = findViewById(R.id.btn_play)
progressBar = findViewById(R.id.progress_bar)

btnPlay.setOnClickListener {
togglePlayback()
}
}

private fun togglePlayback() {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
mediaPlayer.reset()
btnPlay.text = "Play"
} else {
mediaPlayer.setDataSource(audioUrl)
mediaPlayer.prepareAsync()

progressBar.visibility = View.VISIBLE
btnPlay.isEnabled = false

mediaPlayer.setOnPreparedListener {
mediaPlayer.start()
progressBar.visibility = View.GONE
btnPlay.text = "Stop"
btnPlay.isEnabled = true
}
}
}

override fun onDestroy() {
super.onDestroy()
mediaPlayer.release()
}
}

Step 5: Test the audio streaming functionality

  • Run the app on an Android device or emulator.
  • Click the "Play" button to start streaming the audio. The button text should change to "Stop" and the progress bar should appear.
  • Click the "Stop" button to stop the audio streaming.

That's it! You have successfully implemented audio streaming using MediaPlayer in Kotlin Android.