-1

I'm trying to play sequence mp3 files by using array, for and AVQueueplayer. I see this error Expected declaration.

   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
        }()
}`

Expected declaration

    @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()
}
mjk
  • 21
  • 1
  • 6

1 Answers1

2

You need one AVQueuPlayer so try it like this:

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)

Then you can simply use queue.play() or queue.advanceToNextItem() or so

MohyG
  • 1,335
  • 13
  • 25
  • thank you for your help. unfortunately, it doesn't work when I click on the button. there's not error tho. should I try something else? – mjk Oct 21 '19 at 02:08
  • @mjk can you share more of your code ? which button do you mean? – MohyG Oct 21 '19 at 11:18
  • Sure, I added more of my code onto my question. It works in Xcode console but it doesn't work in project. I have mp3 files in project. when I click the autoplay button, anything doesn't happen. No error either. – mjk Oct 21 '19 at 12:15
  • Are you using a real device or simulator? It's also better to initiate your queue player as a lazy var to ensure that it initializes once I will edit my code – MohyG Oct 21 '19 at 12:31
  • I'm using simulator and I added the additional code but it doesn't work either. maybe, if I get a device and use it, it could work on it? – mjk Oct 21 '19 at 13:02
  • yeah give it a try – MohyG Oct 21 '19 at 14:03