问题
I have an implementation using KVO on player.status much like the suggestion documented here.
Here's the relevant bits:
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)
}
}
}
Despite the status, what's returned is still NaN.
Solution:
So it's come to my attention that both AVPlayer AND AVPlayerItem have status properties. By KVO'ing the AVPlayerItem.status property as opposed to the AVPlayer.status like I had done, the duration will be returned properly.
回答1:
So it's come to his attention that both AVPlayer
AND AVPlayerItem
have status properties. By KVO'ing the AVPlayerItem.status property as opposed to the AVPlayer.status like I had done, the duration will be returned properly.
来源:https://stackoverflow.com/questions/43382686/avplayeritem-duration-returns-as-nan-even-after-player-status-readytoplay