检测AVPlayerViewController是否正在播放video或缓冲并向播放器添加覆盖
- 我必须检测video是否在播放或缓冲模式。我从URL加载video。 我已经尝试了下面的代码,我可以追踪一次video开始播放,但不是当它在缓冲状态。
- 另外,我想在我的播放器中添加一个覆盖视图。 我曾尝试在AVPlayer中添加叠加层,但在全屏模式下叠加层消失。
需要一些build议。 提前致谢。 以下是我的代码:
let playerAV = AVPlayerViewController() var player = AVPlayer() player = AVPlayer(URL: url) print(url) playerAV.player = player playerAV.view.frame = CGRectMake(0, 0, self.videoView.frame.width, self.videoView.frame.height) self.addChildViewController(playerAV) self.videoView.addSubview(playerAV.view) playerAV.didMoveToParentViewController(self) playerAV.player?.play() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.notificationObserver(_:)), name:AVPlayerItemDidPlayToEndTimeNotification , object: player.currentItem) _ = UIDevice.beginGeneratingDeviceOrientationNotifications NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.deviceOrientationDidChange(_:)) , name: UIDeviceOrientationDidChangeNotification, object: nil) player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil) player.addPeriodicTimeObserverForInterval(CMTime(value: 1, timescale: 3), queue: dispatch_get_main_queue()) { [weak self] time in self?.handlePlayerStatus(time) } func handlePlayerStatus(time: CMTime) { if player.status == .ReadyToPlay { // buffering is finished, the player is ready to play print("playing") } if player.status == .Unknown{ print("Buffering") } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "rate" { if let rate = change?[NSKeyValueChangeNewKey] as? Float { if player.currentItem!.status == AVPlayerItemStatus.ReadyToPlay{ if rate != 0 && player.error == nil { print("normal playback") } else{ print("playback stopped") } }else if player.currentItem?.status == AVPlayerItemStatus.Unknown{ print("test") } } } print("you are here") }
在这里检查项目
-
检查我的答案: https : //stackoverflow.com/a/38867386/5109911 ,这显示你如何检查如果玩家正在加载缓冲区,检查是否准备好玩你必须检查
player.currentItem.status
和player.status
-
要添加覆盖到AVPlayer我build议使用您的AVPlayer层上面的
UIView
。
我采取了一个稍微不同的方法来解决类似的问题 – 当AVPlayer开始实际播放(在我们的例子中,这是audio播放,但同样的原则适用),更新UI。
我们使用边界时间在播放开始时(特别是1/3秒的播放之后)执行一个模块,以便在可听回放的同时更新UI:
let times = [NSValue(time:CMTimeMake(1,3))] _ = self.player.addBoundaryTimeObserver(forTimes: times, queue: DispatchQueue.main, using: { [weak self] time in // Code to update the UI goes here, eg self?.someUIView.isHidden = false })
我在公司的博客上有更详细的介绍(和一个示例Xcode项目): http : //www.artermobilize.com/blog/2017/02/09/detect-when-ios-avplayer-finishes-buffering -使用-斯威夫特/
至于第二个问题,我同意Marco提出的在AVPlayer层上使用UIView的build议。