如何在Swift中只按一次按钮后播放歌曲列表

问题描述 投票:-1回答:1

我知道如何在按屏幕上的按钮时播放一首歌曲,但不能播放一首歌曲,直到一首歌曲结束后自动播放一首歌曲,直到播放该数组中的所有歌曲为止。

有人提到使用AVQueuePlayer,但我们当中不计其数的人不知道如何实现。你们能否提供有关如何使用它的良好示例代码?

[我按照此视频中的代码在您点击按钮时播放一首歌曲-https://www.youtube.com/watch?v=2kflmGGMBOA

var myQueuePlayer: AVQueuePlayer?
var avItems: [AVPlayerItem] = []

func audio () {

    var items: [String] = ["one", "two", "three", "four", "five"]
    items.shuffle()

    for clip in items {
        guard let url = Bundle.main.url(forResource: clip, withExtension: ".mp3") else {
            // mp3 file not found in bundle - so crash!
            fatalError("Could not load \(clip).mp3")
        }
        avItems.append(AVPlayerItem(url: url))
        //button.isHidden = true
    }

}


@IBAction func didTapButton() {

    audio()
    if myQueuePlayer == nil {

        // instantiate the AVQueuePlayer with all avItems
        myQueuePlayer = AVQueuePlayer(items: avItems)
        print("pup1")
        print(myQueuePlayer!.rate)

    } else {

        // stop the player and remove all avItems
        myQueuePlayer?.removeAllItems()
        // add all avItems back to the player
        avItems.forEach {
                myQueuePlayer?.insert($0, after: nil)
            }

    }
    // seek to .zero (in case we added items back in)
    myQueuePlayer?.seek(to: .zero)
    // start playing
    myQueuePlayer?.play()

}
ios arrays swift avaudioplayer avqueueplayer
1个回答
0
投票

您应该完全可以自行找到它,但这是一个非常简单的示例:

© www.soinside.com 2019 - 2024. All rights reserved.