添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

This example demonstrates how to implement a MediaPlayer class to implement a basic Audio Player in an Android Kotlin app.

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="10dp"
   android:paddingRight="10dp">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="30dp"
      android:text="Now Playing: "
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:textColor="@android:color/holo_red_dark"
      android:textSize="16sp"
      android:textStyle="bold|italic" />
   <TextView
      android:id="@+id/txtSongName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView"
      android:layout_toEndOf="@+id/textView"
      android:textColor="@android:color/background_dark"
      android:textSize="16sp"
      android:textStyle="bold|italic" />
   <ImageButton
      android:id="@+id/btnBackward"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:src="@drawable/ic_back" />
   <ImageButton
      android:id="@+id/btnPlay"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/btnBackward"
      android:layout_marginStart="10dp"
      android:layout_toEndOf="@+id/btnBackward"
      android:src="@drawable/ic_play" />
   <ImageButton
      android:id="@+id/btnPause"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/btnPlay"
      android:layout_marginStart="10dp"
      android:layout_toEndOf="@+id/btnPlay"
      android:src="@drawable/ic_pause" />
   <ImageButton
      android:id="@+id/btnForward"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/btnPause"
      android:layout_marginStart="10dp"
      android:layout_toEndOf="@+id/btnPause"
      android:contentDescription="@+id/imageButton3"
      android:src="@drawable/ic_forward" />
   <TextView
      android:id="@+id/txtStartTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/seekBar"
      android:text="0 min, 0 sec" />
   <SeekBar
      android:id="@+id/seekBar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@+id/btnBackward"
      android:layout_toStartOf="@+id/txtSongTime"
      android:layout_toEndOf="@+id/txtStartTime" />
   <TextView
      android:id="@+id/txtSongTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/seekBar"
      android:layout_toEndOf="@+id/btnForward"
      android:text="0 min, 0 sec " />
</RelativeLayout>

Step 3 − Add the following code to MainActivity.kt

import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
   lateinit var forwardBtn: ImageButton
   lateinit var backwardBtn: ImageButton
   lateinit var pauseBtn: ImageButton
   lateinit var playBtn: ImageButton
   lateinit var mediaPlayer: MediaPlayer
   private lateinit var songName: TextView
   private lateinit var startTime: TextView
   private lateinit var songTime: TextView
   private lateinit var seekBar: SeekBar
   private var handler: Handler = Handler()
   private var onTime: Int = 0
   private var playTime: Int = 0
   private var endTime: Int = 0
   private var forwardTime: Int = 5000
   private var backwardTime: Int = 5000
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      backwardBtn = findViewById(R.id.btnBackward)
      forwardBtn = findViewById(R.id.btnForward)
      playBtn = findViewById(R.id.btnPlay)
      pauseBtn = findViewById(R.id.btnPause)
      songName = findViewById(R.id.txtSongName)
      startTime = findViewById(R.id.txtStartTime)
      songTime = findViewById(R.id.txtSongTime)
      songName.text = "SpeakerBox - Fast & Furious"
      mediaPlayer = MediaPlayer.create(this, R.raw.fast_and_furious)
      seekBar = findViewById(R.id.seekBar)
      seekBar.isClickable = false
      pauseBtn.isEnabled = true
      playBtn.setOnClickListener {
         Toast.makeText(this, "Playing Audio", Toast.LENGTH_SHORT).show()
         mediaPlayer.start()
         endTime = mediaPlayer.duration
         playTime = mediaPlayer.currentPosition
         seekBar.max = endTime
         onTime = 1
         songTime.text = String.format(
            "%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(endTime.toLong()) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()))
         startTime.text = String.format(
            "%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()))
         seekBar.progress = playTime
         handler.postDelayed(updateSongTime, 100)
         pauseBtn.isEnabled = true
         playBtn.isEnabled = false
      btnPause.setOnClickListener {
         mediaPlayer.pause()
         pauseBtn.isEnabled = false
         playBtn.isEnabled = true
         Toast.makeText(applicationContext, "Audio Paused", Toast.LENGTH_SHORT).show()
      btnForward.setOnClickListener {
         if ((playTime + forwardTime) <= endTime) {
            playTime += forwardTime
            mediaPlayer.seekTo(playTime)
          else {
            Toast.makeText(
               applicationContext,
               "Cannot jump forward 5 seconds",
               Toast.LENGTH_SHORT
            ).show()
         if (!playBtn.isEnabled) {
            playBtn.isEnabled = true
      btnBackward.setOnClickListener {
         if ((playTime - backwardTime) > 0) {
            playTime -= backwardTime
            mediaPlayer.seekTo(playTime)
         else {
            Toast.makeText(
               applicationContext,
               "Cannot jump backward 5 seconds",
               Toast.LENGTH_SHORT
            ).show()
         if (!playBtn.isEnabled) {
            playBtn.isEnabled = true
   private val updateSongTime = object : Runnable {
      override fun run() {
         playTime = mediaPlayer.currentPosition
         startTime.text = String.format(
            "%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()
            (TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) - TimeUnit.MINUTES.toSeconds
            (TimeUnit.MILLISECONDS.toMinutes(
                  playTime.toLong()
         seekBar.progress = playTime
         handler.postDelayed(this, 100)
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

  • Related Articles
  • MediaPlayer class to implement a basic Audio Player in an Android App
  • How to create a WebView in an Android App using Kotlin?
  • How to use AutoCompleteTextView in an Android App using Kotlin?
  • Working with RecyclerView in an Android App using Kotlin?
  • How to embed youtube as an audio player?
  • How to call OnDestroy Activity in an Android App using Kotlin?
  • How to create Tab Layout in an Android App using Kotlin?
  • How to create GridView Layout in an Android App using Kotlin?
  • How to work with Camera in an Android App using Kotlin?
  • How to add an audio player to an HTML webpage?
  • How to read a simple text file in an Android App using Kotlin?
  • How to use Calendar Widget using the CalendarView class in Android App using Kotlin?
  • How to Implement SuperBottomBar in Android App?
  • How to create Text to Speech in an Android App using Kotlin?
  • How to convert pixels to dp in an Android App using Kotlin?
  • We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy.