如何检测AVPlayer何时开始/停止在swift中播放

时间:2016-01-20 17:39:40

标签: swift ios9 avplayer avplayerviewcontroller

我在scrollView中有一个AVPlayer,由于某种原因,当AVPlayer播放时,滚动视图会跳到顶部,导致视频在屏幕上不可见,因为视频在滚动视图底部滚动。因此,为了阻止scrollView跳转,我想在用户启动/停止视频时禁用并启用滚动。不确定这是否能解决我的问题,但我希望有人知道为播放器添加观察者或通知的正确方法,以便我可以测试它。

这是我在ViewController中包含一些静态文本和AVPlayer的代码。 以下代码:

    let path = NSBundle.mainBundle().pathForResource("carbon_video", ofType:"mp4")

    let url = NSURL.fileURLWithPath(path!)

    var player = AVPlayerViewController()
    var avPlayer = AVPlayer(URL: url)
    player.player = avPlayer
    self.addChildViewController(player)
    player.view.translatesAutoresizingMaskIntoConstraints = false

    player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: nil)
    player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)

1 个答案:

答案 0 :(得分:0)

我认为这可以帮到你

func playerItemDidReachEnd(notification: NSNotification) {
    let p: AVPlayerItem = notification.object as! AVPlayerItem
    p.seekToTime(kCMTimeZero)
}

override func viewDidAppear(animated: Bool) {
    avPlayer.play()
    paused = false
    // Disable scrolling
}

override func viewDidDisappear(animated: Bool) {
    avPlayer.pause()
    paused = true
// Enable scrolling
}