Simple Music Player App in Kotlin

Let's learn how to create a Music Player Application in android using Kotlin language. We can simply create this with the help of "MediaPlayer" calss. MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network.



Basic Requirements

  • Android Studio 
  • Android Emulator - To run the music player app. 
  • Basic kotlin or programming knowledge

Design Main Activity Layout XML

Modify the default "activity_main.xml" as below. We just simply adding one clickable button or ImageView, which will help us to perform the Play and pause function.

  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

<ImageView
    android:id="@+id/btnPlay"
    android:src="@drawable/ic_baseline_play_circle_outline_24"
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:padding="8dp"
    android:contentDescription="@string/todo" />

</RelativeLayout>
  

Create Raw Directory 

As we are using local audio file create one raw file under the res directory with your audio file. Since we are using audio files from local directory, no other special permissions required in android manifest files.



Complete Coding

Let's complete the Music player application coding by using Media Player Class as we discussed before

   

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView


class MainActivity : AppCompatActivity() {
lateinit var mp : MediaPlayer
lateinit var btnPlay:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 btnPlay = findViewById(R.id.btnPlay)
 mp= MediaPlayer.create(this,R.raw.summer)
 mp.start()
 btnPlay.setImageResource(R.drawable.ic_baseline_pause_circle_outline_24)

btnPlay.setOnClickListener {
 if (mp.isPlaying){
 mp.pause()
 btnPlay.setImageResource(R.drawable.ic_baseline_play_circle_outline_24)
 }else {
    mp.start()
    btnPlay.setImageResource(R.drawable.ic_baseline_pause_circle_outline_24)
    }
  }
 }
}




The above kotlin code will play the audio or mp3 file inside the raw directory automatically while running the app. We can control the music by pressing the button for play and pause. The same button is used here for play and pause and it will change the button image as it is doing its purpose accordingly.

Now Run the Application and See how it is working. Thank you





Comments