由于意外异常而终止应用程序
'NSInternalInconsistencyException',原因:'An instance 0x1702076f0
AVPlayerItem类的被释放,而键值观察员是
还在注册。当前观察信息:
(
(.加载时间范围,选项:上下文:
0x0,属性:0x1748462d0>)'
这是将currentItem.loadedTimeRanges观察者添加到我的AVPlayer后收到的错误

player = AVPlayer(url: videoUrl!)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = postVideoView.frame
        playerLayer.frame.size.width = UIScreen.main.bounds.width
        self.postVideoView.layer.addSublayer(playerLayer)
        player?.play()
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
            DispatchQueue.main.async {
                self.player?.seek(to: kCMTimeZero)
                self.player?.play()
            }
        })
    }


override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    //this is when the player is ready and rendering frames
    if keyPath == "currentItem.loadedTimeRanges" {
        if let duration = player?.currentItem?.duration {
            let seconds = CMTimeGetSeconds(duration)

            let secondsText = Int(seconds) % 60
            let minutesText = String(format: "%02d", Int(seconds) / 60)
            videoLengthLabel.text = "\(minutesText):\(secondsText)"
        }
    }
}

最佳答案

你在哪里叫removeObserver?目前看来,如果你的顶层代码创建了一个新播放器并添加了一个观察者。如果这被调用两次,第一个实例的观察者仍然存在。因此,我希望在顶部出现以下行:

self.player?.removeObserver(self)

如果它没有被调用两次,那么代码中是否还有self.player被重新分配或取消分配的地方?如果是这样,您应该首先调用removeObserver
您还将每次向NotificationCenter添加一个新的观察者。这应该只调用一次,或者在添加另一个之前removeObserver

关于ios - 将观察者添加到播放器时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45473621/

10-13 09:04