Home > Blockchain >  How to automatically play the song after it ends in Kotlin?
How to automatically play the song after it ends in Kotlin?

Time:10-04

So I have my code like this

                var flag = 0
                player = MediaPlayer.create(this,songResources.getValue(songList[flag]).rawId)
                player.start()
                player.setOnCompletionListener {
                    flag              
                    player = MediaPlayer.create(this,songResources.getValue(songList[flag]).rawId)
                    player.start()
                    player.setOnCompletionListener {
                       flag              
                       player=MediaPlayer.create(this,songResources.getValue(songList[flag]).rawId)
                       player.start()
                       player.setOnCompletionListener {
                          //and so on, and so forth. 
                          //assume this is the last song on the list. 
                          //set flag back to 0 and the rest is just like above code
                          flag = 0
                          player=MediaPlayer.create(this,songResources.getValue(songList[flag]).rawId)
                          player.start()
                          player.setOnCompletionListener {// just like above code}
                       }
                    }        
                }

Basically the purpose of the code is after each song in the list ends, it starts the next one. I want to simplify it with for loop, but the problem is, all of the song suddenly playing without waiting the previous song finish. Is there a way to simplify it?

CodePudding user response:

You can use recursion the achieve that, by creating a playSong function which takes the list of songs and the index of the song that are going to play and when that song completed this function is going to call itself with the next index, like that:

fun playSong(songList: List<Int>, flag: Int) {
    player = MediaPlayer.create(this, songResources.getValue(songList[flag]).rawId)
    player.start()
    player.setOnCompletionListener {
        playSong(player, list, if (flag == list.lastIndex) 0 else flag   1)
    }
}

if (flag == list.lastIndex) 0 else flag 1: This means if the completed song is the last song => play the first one; else => play the next one.

  • Related