swift 我想在AVPlayer缓冲时添加活动指示器

izkcnapc  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(77)
private func startVideo() {
    if let url = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4") {
        player = AVPlayer(url: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.view.frame = avPlayerView.bounds
        addChild(playerViewController)
        avPlayerView.addSubview(playerViewController.view)
        playerViewController.didMove(toParent: self)
        player?.play()
    }
}

我需要添加一个活动加载器每当视频缓冲。

lymnna71

lymnna711#

你可以使用下面的代码来实现。观察播放机上的KeyPath可以实现这一点。

var activityIndicator: UIActivityIndicatorView!
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if player != nil {
            player.play()
            player.addObserver(self, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
        }
    }
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int, let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int {
            if #available(iOS 10.0, *) {
                let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
                let newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
                if newStatus != oldStatus {
                   DispatchQueue.main.async {[weak self] in
                       if newStatus == .playing || newStatus == .paused {
                        self!.activityIndicator.stopAnimating()
                       } else {
                        self!.activityIndicator.startAnimating()
                       }
                   }
                }
            } else {
                // Fallback on earlier versions
                self.activityIndicator.stopAnimating()
            }
        }
    }

相关问题