If a person presses the button 10 times, then they will hear 10 different lists of songs being played continuously. I want it to be that if a person presses 10 times, they will only be listening to one list of songs. I'm basically trying to create a reset button.
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($0, after: nil)
}
}
// seek to .zero (in case we added items back in)
myQueuePlayer?.seek(to: .zero)
// start playing
myQueuePlayer?.play()
}
}