2016-07-27 46 views
0

我想檢查AVPlayerViewController是否正在播放視頻或其仍然緩衝。我還希望通過下一個和上一個按鈕在此AVPlayerViewController中添加疊加視圖。 使用下面的代碼我的視頻緩衝,但它顯示正常playback.i想要跟蹤如果它的播放或其暫停或其緩衝階段。檢查AVPlayer的播放狀態並將覆蓋視圖添加到AVPlayerViewController中

let playerAV = AVPlayerViewController() 
    var player = AVPlayer() 
    let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.d e/big_buck_bunny.mp4") 
    player = AVPlayer(URL:videoURL!) 
    playerAV.player = player 
    playerAV.view.frame = self.movieView.frame 
    self.addChildViewController(playerAV) 

    self.movieView.addSubview(playerAV.view) 
    playerAV.didMoveToParentViewController(self) 

    playerAV.contentOverlayView?.addSubview(viewNext) 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.notificationObserver(_:)), name:AVPlayerItemDidPlayToEndTimeNotification , object: player.currentItem) 

    player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil) 
    _ = UIDevice.beginGeneratingDeviceOrientationNotifications 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.deviceOrientationDidChange(_:)) , name: 
     UIDeviceOrientationDidChangeNotification, object: nil) 


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 rate == 0.0 { 
       print("playback stopped") 
      } 
      if rate == 1.0 { 
       print("normal playback") 
      } 
      if rate == -1.0 { 
       print("reverse playback") 
      } 
     } 
    } 
    print("you are here") 
} 

回答

0

爲了檢查你可以添加一個週期性時間觀察球員的狀態:

player.addPeriodicTimeObserverForInterval(CMTime(value: 1, timescale: 3), queue: dispatch_get_main_queue()) { [weak self] time in 
    self?.handlePlayerStatus(time) 
} 

裏面handlePlayerStatus您檢查狀態:

func handlePlayerStatus(time: CMTime) { 
    if player.status == .ReadyToPlay { 
     // buffering is finished, the player is ready to play 
    } 
} 
+0

它仍然沒有工作。 。它仍然緩衝,但accourding到你的handleplayerstatu它說緩衝結束 –

+0

什麼是不工作? – fiks

+0

它仍然在緩衝模式,但/ /緩衝完成後,玩家準備玩正在調用。 –