如何播放序列MP3文件?

时间:2019-10-20 06:33:44

标签: swift xcode avqueueplayer

我正在尝试使用array,for和AVQueueplayer播放序列mp3文件。我看到此错误的预期声明。

   for number in myIndex..<arr.count{
    var queuePlayer: AVQueuePlayer = {

        let url1 = Bundle.main.url(forResource: String(myIndex+number), withExtension: "mp3")!

        let item1 = AVPlayerItem(url: url1)

        let queue = AVQueuePlayer(items: [item1])

        return queue
        }()
}`

预期的声明

    @IBAction func autoplay(_ sender: Any) {


var items : [AVPlayerItem] = []
for number in myIndex..<arr.count {
    let url = Bundle.main.url(forResource: String(number), withExtension: "mp3")!
items.append(AVPlayerItem(url: url))
}
let queue = AVQueuePlayer(items: items)
queue.play()
}

1 个答案:

答案 0 :(得分:1)

您需要一个AVQueuPlayer,因此请尝试以下操作:

lazy var queue : AVQueuePlayer = {
    return AVQueuePlayer()
}()

var items : [AVPlayerItem] = []

for number in myIndex..<arr.count{
    let url = Bundle.main.url(forResource: String(myIndex+number), withExtension: "mp3")!
    items.append(AVPlayerItem(url: url))
}
queue = AVQueuePlayer(items: items)

然后,您只需使用queue.play()queue.advanceToNextItem()左右