Iam Wayne
Iam Wayne

Reputation: 561

AVQueuePlayer Current Item Changed

I am using QueuePlayer to play a list of songs and the songs are playing. My issue is that I am trying to track whenever the current item changes. I try adding an observer to the QueuePlayer, but this isn't working. The observing func isn't getting called. Any help would be appreciated

Observer

 queuePlayer.currentItem?.addObserver(self, forKeyPath: "currentItem", options: [.new, .old], context: nil)
    }

Listening for observer // Not getting called when item changes

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "currentItem" {
        if let oldItem = change?[NSKeyValueChangeKey.oldKey] as? AVPlayerItem {
            print("Old item : \(oldItem)")
        }

        if let newItem = change?[NSKeyValueChangeKey.newKey] as? AVPlayerItem {
            print("New item : \(newItem)")
        }    
    }
}

Upvotes: 2

Views: 2290

Answers (2)

Awais Fayyaz
Awais Fayyaz

Reputation: 2415

If you need to know when an item finished playing, you can go something like.

Inside your viewdidload(), add observer

NotificationCenter.default.addObserver(self, selector: #selector(itemDidPlayToEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

@objc func itemDidPlayToEnd() {

    //your item played to end
  }

I Just verified that its working fine

This may also be helpful

Upvotes: -1

Ashley Mills
Ashley Mills

Reputation: 53121

Your code is observing the currentItem property of queuePlayer.currentItem.

To observe the currentItem property of queuePlayer, it should be

queuePlayer.addObserver(self, forKeyPath: "currentItem", …

or better yet, for compile time checking…

queuePlayer.addObserver(self, forKeyPath: #keyPath(AVQueuePlayer.currentItem), …

Upvotes: 2

Related Questions