-1

I'm writing a wrapper to create an Audio player using AVQueuePlayer. I want to be able to update the items (update the playlist, add, remove from playlist...) the only way that I have found is this:

var audioPlayer = AVQueuePlayer()

public var playerItems : [AVPlayerItem] = [] {
    didSet {
        self.audioPlayer.removeAllItems()
        playerItems.forEach({ self.audioPlayer.insert($0, after: nil)})
    }
}
iOSGeek
  • 5,115
  • 9
  • 46
  • 74

1 Answers1

0

You can just create new instance of AVQueuePlayer:

public var playerItems: [AVPlayerItem] = [] {
    didSet {
        self.audioPlayer = AVQueuePlayer(items: playerItems)
    }
}

But if you want to remove/update/insert items, you need to write separate methods for it.

For example:

func remove(at index: Int) {
    guard self.audioPlayer.items().indices ~= index else { return }
    let item = self.audioPlayer.items()[index]
    self.audioPlayer.remove(item)
}
Ilya Kharabet
  • 4,203
  • 3
  • 15
  • 29
  • When creating new instance I will need to remove observation and register observation again ... I think the current solution is better – iOSGeek Feb 10 '18 at 22:43
  • 1
    Than you need to write methods like `func remove(at index: Int)` from my answer. I think there is no better solution. – Ilya Kharabet Feb 11 '18 at 07:29