【问题标题】:how to get CurrentItem.duration without getting nan如何在不获取 nan 的情况下获取 CurrentItem.duration
【发布时间】:2019-08-29 17:38:14
【问题描述】:

我关注了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()
        }
    }
}

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

感谢您的宝贵时间。

【问题讨论】:

    标签: swift uiview avplayer


    【解决方案1】:

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

    CMTimeGetSeconds(player.currentItem!.asset.duration)
    

    它会给你当前播放项目的持续时间,以秒为单位。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2020-08-08
      • 2023-03-17
      相关资源
      最近更新 更多