我在player.status上使用KVO的实现很像记录here的建议。
以下是相关位:
var player: AVPlayer?
var url = URL(string: "some video url")!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayer()
}
func initializeVideoPlayer() {
let playerItem = AVPlayerItem(url: url)
self.player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.layer.bounds
videoView.layer.addSublayer(playerLayer)
player?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "status" {
if player?.status == .readyToPlay {
print(player?.currentItem?.duration)
print(CMTimeGetSeconds((player?.currentItem?.duration)!))
// let videoLength = CMTimeGetSeconds((player?.currentItem?.duration)!)
// videoProgressSlider.maximumValue = Float(videoLength)
}
}
}
尽管状态如此,但返回的内容仍然是NaN。
解决方案:
因此,我注意到AVPlayer和AVPlayerItem都具有状态属性。通过KVO获取AVPlayerItem.status属性而不是像我所做的AVPlayer.status,持续时间将正确返回。
答案 0 :(得分:2)
所以他注意到AVPlayer
和AVPlayerItem
都有状态属性。通过KVO'ing AVPlayerItem.status属性而不是像我所做的AVPlayer.status,持续时间将正确返回。