Skip to main content

How to implement media controls (play, pause, stop) using MediaPlayer in Kotlin Android

How to implement media controls (play, pause, stop) using MediaPlayer in Kotlin Android.

Here's a step-by-step tutorial on how to implement media controls (play, pause, stop) using MediaPlayer in Kotlin Android:

Step 1: Set up your project

Create a new project in Android Studio and set up the necessary dependencies in your app-level build.gradle file. Add the following line to the dependencies block:

implementation 'androidx.media:media:1.4.1'

Step 2: Add the MediaPlayer instance

In your activity or fragment, declare a MediaPlayer instance as a class variable:

private var mediaPlayer: MediaPlayer? = null

Step 3: Initialize the MediaPlayer

In your activity's onCreate() or fragment's onViewCreated() method, initialize the MediaPlayer instance:

mediaPlayer = MediaPlayer.create(context, R.raw.your_audio_file)

Replace R.raw.your_audio_file with the resource ID of your audio file. You can also use a URL or file path instead of a resource ID.

Step 4: Implement media controls

To implement media controls, you can add buttons or other UI elements to your layout. For example, you can add three buttons for play, pause, and stop:

<Button
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />

<Button
android:id="@+id/btn_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />

<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop" />

Step 5: Set click listeners for the buttons

In your activity or fragment, set click listeners for the play, pause, and stop buttons:

val btnPlay = findViewById<Button>(R.id.btn_play)
val btnPause = findViewById<Button>(R.id.btn_pause)
val btnStop = findViewById<Button>(R.id.btn_stop)

btnPlay.setOnClickListener {
mediaPlayer?.start()
}

btnPause.setOnClickListener {
mediaPlayer?.pause()
}

btnStop.setOnClickListener {
mediaPlayer?.stop()
mediaPlayer?.prepare()
mediaPlayer?.seekTo(0)
}

Step 6: Release the MediaPlayer

To release the MediaPlayer instance when it's no longer needed, override the activity's onDestroy() or fragment's onDestroyView() method:

override fun onDestroy() {
super.onDestroy()
mediaPlayer?.release()
mediaPlayer = null
}

That's it! You have now implemented media controls using MediaPlayer in Kotlin Android. You can customize the behavior of the buttons and add additional features as per your requirements.