如何在不获取 nan 的情况下获取 CurrentItem.duration

how to get CurrentItem.duration without getting nan

我正在关注 A simple iOS view to play video,它可以帮助您在 UIView 中显示 AVPlayer。这非常有帮助,但不幸的是,在 VideoView(自定义创建)中它没有包含 currentItem?.duration 所以,我试着自己用这种方式添加它:

   func getCurrentItemDuration() -> Double
    {
        let duration = player?.currentItem?.duration
        let durationSeconds = CMTimeGetSeconds(duration!)
        return durationSeconds
    }  

但是当我尝试在 UIViewController 中打印它时,我得到:Nan

class VideoView: UIView {
    
    var playerLayer: AVPlayerLayer?
    var player: AVPlayer?
    var isLoop: Bool = false
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)    
    }
    
    func configure(url: String) {
        if let videoURL = URL(string: url) {
            
     
            player = AVPlayer(url: videoURL)
            playerLayer = AVPlayerLayer(player: player)
            playerLayer?.frame = bounds
            playerLayer?.videoGravity = AVLayerVideoGravity.resize

            if let playerLayer = self.playerLayer {
                layer.addSublayer(playerLayer)
            }
            NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
        }
    }
    
    func play() {
        if player?.timeControlStatus != AVPlayer.TimeControlStatus.playing {
            player?.play()
        }
    }
    
    func pause() {
        player?.pause()
    }
    
    func stop() {
        player?.pause()
        player?.seek(to: CMTime.zero)
    }

     func getCurrentItemDuration() -> Double
    {
        let duration = player?.currentItem?.duration
        let durationSeconds = CMTimeGetSeconds(duration!)
        return durationSeconds
    }
    @objc func reachTheEndOfTheVideo(_ notification: Notification) {
        if isLoop {
            player?.pause()
            player?.seek(to: CMTime.zero)
            player?.play()
        }
    }
}

我不知道如何修复这个错误,所以如果有人熟悉这个错误,请指导我修复它。 :)

感谢您的宝贵时间。

因为你想获得资产的持续时间。所以,尝试使用 :

CMTimeGetSeconds(player.currentItem!.asset.duration)

它将以秒为单位为您提供当前播放项目的持续时间。