androidaudiokotlinbackground-music

How to play background music through all activities using Kotlin?


How can I play a music file in the background through all activities by using Kotlin? I have looked everywhere but I only found solutions for Java not for Kotlin.

I tried using this function but I don't know how to use it:

fun playSound() {
    try {
        if (m.isPlaying()) {
            m.stop()
            m.release()
            //m = MediaPlayer()
        }

        val descriptor = assets.openFd("backgroundsound1.mp3")
        m.setDataSource(descriptor.fileDescriptor, descriptor.startOffset, descriptor.length)
        descriptor.close()

        m.prepare()
        m.setVolume(1f, 1f)
        m.setLooping(true)
        m.start()
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

Solution

  • Here' code in kotlin code Play background music in all activities

    class BackgroundSoundService : Service() {
        internal lateinit var player: MediaPlayer
        override fun onBind(arg0: Intent): IBinder? {
    
            return null
        }
    
        override fun onCreate() {
            super.onCreate()
           val afd = applicationContext.assets.openFd("backgroundsound1.wav") as AssetFileDescriptor
        val player = MediaPlayer()
        player.setDataSource(afd.fileDescriptor)
            player.isLooping = true // Set looping
            player.setVolume(100f, 100f)
    
        }
    
        override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
            player.start()
            return 1
        }
    
        override fun onStart(intent: Intent, startId: Int) {
            // TO DO
        }
    
        fun onUnBind(arg0: Intent): IBinder? {
            // TO DO Auto-generated method
            return null
        }
    
        fun onStop() {
    
        }
    
        fun onPause() {
    
        }
    
        override fun onDestroy() {
            player.stop()
            player.release()
        }
    
        override fun onLowMemory() {
    
        }
    
        companion object {
            private val TAG: String? = null
        }
    }