How to play media player based on list index?

Issue

I have a song list and I want to play it in order. So after the song ends, it plays the next song. Here’s what I try so far in my MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    var flag = 0
    //play the first song
    player = MediaPlayer.create(this,songResources.getValue(songList[0]).rawId)
    player.start()

    //play the next song in order after each of the song ends
    player.setOnCompletionListener {
        flag++
        player = MediaPlayer.create(this,songResources.getValue(songList[flag]).rawId)
        player.start()
}

After the first song ends, the second song starts playing. But after the second song ends, the third song didn’t start playing. How can I fix this?

Solution

It looks like you just need to set your flag variable as a class level variable (i.e. not inside the onCreate() function).

Try declaring private var flag = 0 above onCreate() and see if that works.

Answered By – JTODR

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

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