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

How to play a list of songs after pressing a button just once in Swift

我知道如何在您按下屏幕上的按钮时播放一首歌曲,而不是播放一组歌曲,其中一首歌曲在一首歌曲结束后自动播放,直到播放完数组中的所有歌曲。

有人提到使用 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([=11=], after: nil)
            }

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

}

你自己找到这个应该没有问题,但这里有一个非常简单的例子:

import AVFoundation

class TestAVQueuViewController: UIViewController {

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

    override func viewDidLoad() {
        super.viewDidLoad()

        // assuming I have 4 .mp3 files in the bundle, named:
        let mySongs: [String] = [
            "clip1", "clip2", "clip3", "clip4",
        ]

        for clip in mySongs {
            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))
        }

    }

    @IBAction func didTap(_ sender: Any) {
        // if first time
        if myQueuePlayer == nil {
            // instantiate the AVQueuePlayer with all avItems
            myQueuePlayer = AVQueuePlayer(items: avItems)
        } else {
            // stop the player and remove all avItems
            myQueuePlayer?.removeAllItems()
            // add all avItems back to the player
            avItems.forEach {
                myQueuePlayer?.insert([=10=], after: nil)
            }
        }
        // seek to .zero (in case we added items back in)
        myQueuePlayer?.seek(to: .zero)
        // start playing
        myQueuePlayer?.play()
    }

}

编辑

更新了代码以演示在点击按钮时播放剪辑,并在进一步点击按钮时重新启动剪辑。