如何检查我的AVPlayer是否正在缓冲?对于AVPlayer

时间:2018-09-10 12:19:22

标签: ios swift avplayer

我想检测我的AVPlayer是否正在为当前位置缓冲,以便可以显示装载程序或其他内容。但是我似乎在AVPlayer的文档中找不到任何内容。 我正在使用此代码,但它不起作用:

playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil)
playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil)
playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .New, context: nil)

override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if object is AVPlayerItem {
        switch keyPath {
            case "playbackBufferEmpty":
               // Show loader

            case "playbackLikelyToKeepUp":
                // Hide loader

            case "playbackBufferFull":
                // Hide loader
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

    player?.currentItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
    player?.currentItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
    player?.currentItem?.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)


override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if keyPath == "playbackBufferEmpty" {

        print("Show loader")

    } else if keyPath == "playbackLikelyToKeepUp" {

        print("Hide loader")

    } else if keyPath == "playbackBufferFull" {
        print("Hide loader")
    }
}