AVPlayerItem.duration returns as NaN even after player.status == .readyToPlay

霸气de小男生 提交于 2019-12-24 05:54:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!