Hi friends, today in this Android Mediaplayer Kotlin Tutorial we will learn how to make an Android Media Player using Kotlin Mediaplayer example and we will make use of MediaPlayer class in Android. So, lets start working on our MediaPlayer Example In Kotlin.
What is Android MediaPlayer Class:
In Android Studio MediaPlayer class is a class that allows to access video or audio files using resources. We can access any audio/video file from our system . Also from a data stream over network.
The common methods of the MediaPlayer Class are:
- getDuration()
- getCurrentPosition()
- setVolume()
- pause()
- isPlaying()
MediaPlayer Example in Kotlin:
1- For our Mediaplayer Kotlin example first we start with a new Android Studio Project and name it as “KotlinMediaPlayer”. The name of the Android Project totally depends on your choice.
2- I have selected the API level to 19. Because, it will help you to run your application on almost 98% of the Android devices. But, if you want to select any higher level API you can change the API level from the list.

3- So after your project builds, you will have two files. “MainActivity.kt” file and “activity_main.xml” file. First we will design the UI of our Android Player in activity_main.xml file.

(Media Player Kotlin)
“activity_main.xml”
4- First change the default layout from Constrain Layout to Relative Layout. Then, in our activity_main file we need some widgets. TextView, ImageView, ImageButton and SeekBar. First we will use two TextViews at the top. One to display “Now Playing” and second one to display the name of that song/audio etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<TextView android:id="@+id/now_playing" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Now Playing: " android:layout_marginTop="30dp" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/song_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/now_playing" android:layout_toRightOf="@+id/now_playing" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" /> |
5- Below the name of the song/audio we will use an ImageView to set the background image of the Media Player. For doing this first come to res –> drawable and add the image in your drawable folder that you want to set as your background image. Use that image to set it in the background of your ImageView.
1 2 3 4 5 6 7 8 |
<ImageView android:id="@+id/player_image" android:layout_width="match_parent" android:layout_height="450dp" android:layout_below="@+id/now_playing" android:layout_above="@+id/start_time" android:layout_marginTop="10dp" android:src="@drawable/mp" /> |
6- So, now we have to use 4 ImageButtons. With these ImageButtons we will handle the Play, Pause, Forward and Backward functions of the player.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<ImageButton android:id="@+id/backButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="44dp" android:layout_marginLeft="20dp" android:src="@android:drawable/ic_media_rew" /> <ImageButton android:id="@+id/buttonPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/backButton" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/backButton" android:src="@android:drawable/ic_media_play" /> <ImageButton android:id="@+id/buttonPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/buttonPlay" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/buttonPlay" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/buttonForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/buttonPause" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/buttonPause" android:contentDescription="@+id/imageButton3" android:src="@android:drawable/ic_media_ff" /> |
7- We will add two TextViews to show the start time and end time of the audio file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<TextView android:id="@+id/start_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/seekbar" android:textSize="10sp" android:textColor="#000000" android:text="0 min, 0 sec" /> <TextView android:id="@+id/song_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10sp" android:textColor="#000000" android:layout_toRightOf="@+id/buttonForward" android:layout_alignTop="@+id/seekbar" android:text="0 min, 0 sec" /> |
8- So, in the last we will add a SeekBar to handle the progress of the audio.
1 2 3 4 5 6 7 |
<SeekBar android:id="@+id/seekbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/backButton" android:layout_toLeftOf="@+id/song_time" android:layout_toRightOf="@+id/start_time" /> |
9- And the final activity_main.xml file will look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="10dp" android:paddingRight="10dp" tools:context=".MainActivity"> <TextView android:id="@+id/now_playing" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Now Playing: " android:layout_marginTop="30dp" android:textColor="#000000" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/song_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/now_playing" android:layout_toRightOf="@+id/now_playing" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" android:text="TextView" /> <ImageView android:id="@+id/player_image" android:layout_width="match_parent" android:layout_height="450dp" android:layout_below="@+id/now_playing" android:layout_above="@+id/start_time" android:layout_marginTop="10dp" android:src="@drawable/mp" /> <ImageButton android:id="@+id/backButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="44dp" android:layout_marginLeft="20dp" android:src="@android:drawable/ic_media_rew" /> <ImageButton android:id="@+id/buttonPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/backButton" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/backButton" android:src="@android:drawable/ic_media_play" /> <ImageButton android:id="@+id/buttonPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/buttonPlay" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/buttonPlay" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/buttonForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/buttonPause" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/buttonPause" android:contentDescription="@+id/imageButton3" android:src="@android:drawable/ic_media_ff" /> <TextView android:id="@+id/start_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/seekbar" android:textSize="10sp" android:textColor="#000000" android:text="0 min, 0 sec" /> <SeekBar android:id="@+id/seekbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/backButton" android:layout_toLeftOf="@+id/song_time" android:layout_toRightOf="@+id/start_time" /> <TextView android:id="@+id/song_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10sp" android:textColor="#000000" android:layout_toRightOf="@+id/buttonForward" android:layout_alignTop="@+id/seekbar" android:text="0 min, 0 sec" /> </RelativeLayout> |
Mediaplayer Android Example:
“MainActivity.kt”
10- After working with our activity_main.xml file now we have to add Kotlin code in our MainActivity.kt file. First of all go to res folder and under res folder you will have a folder named raw. Add your audio file in this raw folder. If you don’t have a raw folder under your res folder then right click on res folder and select “Android Resource Directory”. Name the new directory as “raw“.

11- After adding your audio file in the raw folder now we will add some variables (var) and val to set the default start time and end time in seconds. We set forward and backward time as 5 seconds by default. Also we are going to set up a handler to handle the progress of the SeekBar.
1 2 3 4 5 6 7 |
var mPlayer: MediaPlayer? = null private var oTime = 0 private var sTime: Int = 0 private var eTime: Int = 0 private var fTime: Int = 5000 private var bTime: Int = 5000 private val hdlr: Handler = Handler() |
12- So now in onCreate function we will display the title of the audio file. The name of the audio is “fatiha” on my case. Also we will disable the Pause button.
1 2 3 4 5 |
song_name.text = "Fatiha" mPlayer = MediaPlayer.create(this, R.raw.fatiha) seekbar!!.setClickable(false) buttonPause!!.isEnabled = false |
Setting up onClickListeners on ImageButtons:-
13- Now we have to set onClickListener for our ImageButton. On our Play button which has id (buttonPlay) we are going to set a few things. First we get the current start and end time of the MediaPlayer and convert it into Int (Integer Value). We define an if-else condition so that the MediaPlayer cannot move behind on start and cannot move ahead after end.
After that we will set the current position and the total duration of the audio file into our TextView. Handler will update the SeekBar on every 100 milliseconds and the Pause button will be enabled after the MediaPlayer starts playing the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
buttonPlay!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { Toast.makeText(this@MainActivity, "Audio Playing", Toast.LENGTH_SHORT).show() mPlayer!!.start() eTime = mPlayer!!.duration.toLong().toInt() sTime = mPlayer!!.currentPosition.toLong().toInt() if (oTime == 0) { seekbar!!.setMax(eTime) oTime = 1 } song_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(eTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(eTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(eTime.toLong()))) start_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(sTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()))) seekbar?.setProgress(sTime) hdlr.postDelayed(updateSongTime, 100) buttonPause!!.isEnabled = true buttonPlay!!.isEnabled = false } }) |
14- After that now we set an onClickListener for our Pause button which has an id (buttonPause). We will display a Toast message “Audio Paused” whenever the audio will be paused by the user. Also we will enable the Play button and disable the Pause Button.
1 2 3 4 5 6 7 8 |
buttonPause!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { mPlayer!!.pause() buttonPause!!.isEnabled = false buttonPlay!!.isEnabled = true Toast.makeText(applicationContext, "Audio Paused", Toast.LENGTH_SHORT).show() } }) |
15- Now we apply an onClickListener on our Forward Button which has an id (butonForward). So, Forward Button will move the SeekBar 5 seconds ahead of the current position. But, at the end if the MediaPlayer is unable to move 5 seconds ahead it will display a Toast message “Cannot jump forward 5 seconds”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
buttonForward?.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { if (sTime + fTime <= eTime) { sTime = sTime + fTime mPlayer!!.seekTo(sTime) } else { Toast.makeText( applicationContext, "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT ).show() } if (!buttonPlay!!.isEnabled) { buttonPlay!!.isEnabled = true } } }) |
16- After that now we add an onClickListener on our Back Button which has an id (backButton). Since, it will move the MediaPlayer 5 seconds behind from the current position but if it can’t move 5 seconds behind it will display a Toast message “Cannot jump backward 5 seconds”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
backButton!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { if (sTime - bTime > 0) { sTime = sTime - bTime mPlayer!!.seekTo(sTime) } else { Toast.makeText( applicationContext, "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT ).show() } if (!buttonPlay!!.isEnabled) { buttonPlay!!.isEnabled = true } } }) |
Handling The SeekBar:-
17- To handle the SeekBar according to the current position of the MediaPlayer we use function setOnSeekBarChangeListener(). Because SeekBar is responsible to move according to the MediaPlayer. seekbar is the id of our SeekBar in XML.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { mPlayer!!.seekTo(progress) } } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) |
18- After handling our SeekBar now at the end we have to set a function setOnCompletionListener() on our MediaPlayer. Because of this MediaPlayer will start again from the beginning and the current duration will be updated as well.
1 2 3 4 5 6 7 8 9 10 11 12 |
mPlayer!!.setOnCompletionListener(object : MediaPlayer.OnCompletionListener { override fun onCompletion(mp: MediaPlayer?) { try { mPlayer!!.start() seekbar.progress = sTime mPlayer!!.isLooping = true } catch (e: Exception) { Toast.makeText(this@MainActivity, e.toString(), Toast.LENGTH_SHORT).show() } } }) |
19- Finally outside our onCreate method we will make a Runnable object to handle the current position of the SeekBar according to the MediaPlayer. This will update the current position of our SeekBar on every 100 milliseconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private val updateSongTime: Runnable = object : Runnable { override fun run() { sTime = mPlayer!!.currentPosition start_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(sTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()) ) ) seekbar!!.progress = sTime hdlr.postDelayed(this, 100) } } |
20- So, this is all for our MediaPlayer example in Kotlin. Our final MainActivity.kt file will look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
package com.example.kotlinmediaplayer import android.media.MediaPlayer import android.os.Bundle import android.os.Handler import android.view.View import android.widget.SeekBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.lang.Exception import java.lang.String import java.util.concurrent.TimeUnit class MainActivity : AppCompatActivity() { var mPlayer: MediaPlayer? = null private var oTime = 0 private var sTime: Int = 0 private var eTime: Int = 0 private var fTime: Int = 5000 private var bTime: Int = 5000 private val hdlr: Handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) song_name.text = "Fatiha" mPlayer = MediaPlayer.create(this, R.raw.fatiha) seekbar!!.setClickable(false) buttonPause!!.isEnabled = false buttonPlay!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { Toast.makeText(this@MainActivity, "Audio Playing", Toast.LENGTH_SHORT).show() mPlayer!!.start() eTime = mPlayer!!.duration.toLong().toInt() sTime = mPlayer!!.currentPosition.toLong().toInt() if (oTime == 0) { seekbar!!.setMax(eTime) oTime = 1 } song_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(eTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(eTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(eTime.toLong()))) start_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(sTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()))) seekbar?.setProgress(sTime) hdlr.postDelayed(updateSongTime, 100) buttonPause!!.isEnabled = true buttonPlay!!.isEnabled = false } }) buttonPause!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { mPlayer!!.pause() buttonPause!!.isEnabled = false buttonPlay!!.isEnabled = true Toast.makeText(applicationContext, "Audio Paused", Toast.LENGTH_SHORT).show() } }) buttonForward?.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { if (sTime + fTime <= eTime) { sTime = sTime + fTime mPlayer!!.seekTo(sTime) } else { Toast.makeText( applicationContext, "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT ).show() } if (!buttonPlay!!.isEnabled) { buttonPlay!!.isEnabled = true } } }) backButton!!.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { if (sTime - bTime > 0) { sTime = sTime - bTime mPlayer!!.seekTo(sTime) } else { Toast.makeText( applicationContext, "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT ).show() } if (!buttonPlay!!.isEnabled) { buttonPlay!!.isEnabled = true } } }) seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { mPlayer!!.seekTo(progress) } } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) mPlayer!!.setOnCompletionListener(object : MediaPlayer.OnCompletionListener { override fun onCompletion(mp: MediaPlayer?) { try { mPlayer!!.start() seekbar.progress = sTime mPlayer!!.isLooping = true } catch (e: Exception) { Toast.makeText(this@MainActivity, e.toString(), Toast.LENGTH_SHORT).show() } } }) } private val updateSongTime: Runnable = object : Runnable { override fun run() { sTime = mPlayer!!.currentPosition start_time!!.text = String.format( "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()), TimeUnit.MILLISECONDS.toSeconds(sTime.toLong()) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(sTime.toLong()) ) ) seekbar!!.progress = sTime hdlr.postDelayed(this, 100) } } } |
Finally, here we complete our tutorial on MediaPlayer Example in Kotlin. If you have any queries regarding Kotlin media player then you can ask in the comments section below. If you need to know more about Kotlin mediaplayer or on how Android Mediaplayer example works you can read official Android documentation on developers website.
OUTPUT





More Tutorials On Android:-