Achieve smooth video scrubbing with AVPlayer

前端 未结 4 1628
你的背包
你的背包 2021-01-02 02:30

I am trying to achieve smooth video scrubbing with AVPlayer through UISlider I have searched and it seems Apple has a Technical Q&A and explain

4条回答
  •  礼貌的吻别
    2021-01-02 03:12

    I know this is an old problem, I encountered it too. The solution can help someone now. Apple sample make slider super smooth and pretty. To make the sample work:

    private static var context = 1
    func playVideo() {
      ...
      player.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.status), options: [.new, .initial], context: &VideoViewController.context)
      ...
     }
    
    override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let keyPath = keyPath else { return }
        guard context == &VideoViewController.context else { return }
        switch keyPath {
        case #keyPath(AVPlayer.currentItem.status):
            if let newStatus = change.map({ $0[.newKey] as? NSNumber }), 
               let parsedNewStatus = newStatus.map({ AVPlayerItem.Status(rawValue: $0.intValue) ?? .unknown})  {
                playerCurrentItemStatus = parsedNewStatus
            } else {
                playerCurrentItemStatus = .unknown
            }
        default: break
        }
    }
    

    Observe and update playerCurrentItemStatus

提交回复
热议问题