简体   繁体   English

如何根据列表索引播放媒体播放器?

[英]How to play media player based on list index?

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到目前为止,这是我在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?我怎样才能解决这个问题?

It looks like you just need to set your flag variable as a class level variable (ie not inside the onCreate() function).看起来您只需要将标志变量设置为 class 级别变量(即不在 onCreate() 函数内)。

Try declaring private var flag = 0 above onCreate() and see if that works.尝试在 onCreate() 上方声明private var flag = 0并查看是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM