【问题标题】:AVQueuePlayer Current Item ChangedAVQueuePlayer 当前项目已更改
【发布时间】:2018-08-21 16:46:13
【问题描述】:

我正在使用 QueuePlayer 播放歌曲列表并且歌曲正在播放。我的问题是我试图跟踪当前项目何时更改。 我尝试向 QueuePlayer 添加观察者,但这不起作用。观察函数没有被调用。任何帮助将不胜感激

观察者

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

监听观察者 // 当项目改变时不被调用

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)")
        }    
    }
}

【问题讨论】:

    标签: swift avfoundation avplayer avplayeritem avqueueplayer


    【解决方案1】:

    您的代码正在观察queuePlayer.currentItemcurrentItem 属性。

    观察queuePlayercurrentItem属性,应该是

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

    或者更好的是,用于编译时检查……

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

    【讨论】:

    • 感谢您的回复。我试过你的回答“queuePlayer.addObserver(self, forKeyPath: "currentItem", ...这不起作用,观察者函数仍然没有被调用。
    【解决方案2】:

    如果您需要知道某个项目何时结束播放,您可以使用类似的方法。

    在您的viewdidload() 中,添加观察者

    NotificationCenter.default.addObserver(self, selector: #selector(itemDidPlayToEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    
    @objc func itemDidPlayToEnd() {
    
        //your item played to end
      }
    

    我刚刚验证它工作正常

    This may also be helpful

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      相关资源
      最近更新 更多