Categories
Mastering Development

Media Player has not been initialized but song is playing

I added a song to my app using MediaPlayer, like that:

class BackgroundSongService : Service() {
    private lateinit var mediaPlayer: MediaPlayer
    private var length = 0

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        mediaPlayer = MediaPlayer.create(this, R.raw.bonte_song)
        mediaPlayer.isLooping = true
        mediaPlayer.setVolume(20f, 20f)
    }

    override fun onDestroy() {
        mediaPlayer.stop()
        mediaPlayer.release()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mediaPlayer.start()
        Log.d("test", "test")
        return startId
    }

    fun pauseMusic() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
            length = mediaPlayer.currentPosition
        }
    }

    fun resumeMusic() {
        if (!mediaPlayer.isPlaying) {
            mediaPlayer.seekTo(length)
            mediaPlayer.start()
        }
    }

    fun stopMusic() {
        mediaPlayer.stop()
        mediaPlayer.release()
    }

}

And I’m playing it by that (using firebase):

override fun onDataChange(dataSnapshot: DataSnapshot) {
                if (dataSnapshot.child(0.toString()).child("songOn").value.toString() == "true") {
                    val intent = Intent(this@SkyActivity, BackgroundSongService::class.java)
                    startService(intent)
                }
            }

It works. The sound is being played, but everytime I minimize my app/go to home/go to another app, I get an exception:

Unable to pause activity {MyActitivity}: Caused by: kotlin.UninitializedPropertyAccessException: lateinit property mediaPlayer has not been initialized

I’m pausing it like that:

    override fun onPause() {
    super.onPause()
    BackgroundSongService().pauseMusic()
}

The exception happens in the if condition of pauseMusic().
How can mediaPlayer have not been initialized if the music is playing?

Leave a Reply

Your email address will not be published. Required fields are marked *