Kotlin MP3 Player Example

 First   we add the following permission to the Manifest file

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Then we add the following libraries to Gradle Dependencies


implementation ("androidx.media3:media3-exoplayer:1.2.1")
implementation ("androidx.media3:media3-ui:1.2.1")
implementation ("androidx.media3:media3-common:1.2.1")
implementation( "androidx.media3:media3-session:1.2.1")


We synchronize them (we SYNC).


 We add the following "val" into the Main Activity.

val player = ExoPlayer.Builder(context).build()
val mediaSession = MediaSession.Builder(context, player).build()
To take this player to a more advanced level
We add the following code into the main activity.
class PlaybackService : MediaSessionService() {
   
private var mediaSession: MediaSession? = null

   
// Create your Player and MediaSession in the onCreate lifecycle event
   
override fun onCreate() {
       
super.onCreate()
       
val player = ExoPlayer.Builder(this).build()
        mediaSession
= MediaSession.Builder(this, player).build()
   
}

   
// Remember to release the player and media session in onDestroy
   
override fun onDestroy() {
        mediaSession
?.run {
            player
.release()
            release
()
            mediaSession
= null
       
}
       
super.onDestroy()
   
}
}
For more features
 add this
// This example always accepts the connection request
override fun onGetSession(
    controllerInfo
: MediaSession.ControllerInfo
): MediaSession? = mediaSession
or for new features
add these codes
override fun onStart() {
 
val sessionToken = SessionToken(this, ComponentName(this, PlaybackService::class.java))
 
val controllerFuture = MediaController.Builder(this, sessionToken).buildAsync()
  controllerFuture
.addListener(
   
{
       
// Call controllerFuture.get() to retrieve the MediaController.
       
// MediaController implements the Player interface, so it can be
       
// attached to the PlayerView UI component.
        playerView
.setPlayer(controllerFuture.get())
     
},
   
MoreExecutors.directExecutor()
 
)
}

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos