持续时间不是来自AVPlayer currentItem

时间:2016-11-25 03:58:22

标签: ios swift avplayer duration

您好我正在使用AVPlayer进行视频流播放。这就是我要做的事情。

avPlayer = AVPlayer(url: videoURL! as URL)
playerLayer = AVPlayerLayer(player: avPlayer)
playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill
avPlayer.play()

现在我想在视频播放时添加UISlider来移动。所以我这样做了。

let minimumValue:Float=0.00
sliderBar.minimumValue=minimumValue
playerLayer.frame = self.viewPlayer.bounds

self.viewPlayer.layer.addSublayer(playerLayer)
let duration : CMTime = avPlayer.avPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)

sliderBar.maximumValue=Float(seconds)

但是当我打印duration这是我的输出

(lldb) po duration

▿ CMTime
 - value : 0
 - timescale : 0
▿ flags : CMTimeFlags
  - rawValue : 17
 - epoch : 0

如何获取此流媒体视频的持续时间。 请帮我。 谢谢

1 个答案:

答案 0 :(得分:1)

 if let duration = avPlayer?.currentItem?.duration {
            let seconds = CMTimeGetSeconds(duration)

                if seconds.isFinite{
                    let second = Int(seconds)
                    let secondsText = second % 60
                    var secondString = "00"
                    if secondsText < 10{
                        secondString = "0\(secondsText)"
                    }
                    else{
                        secondString = "\(secondsText)"
                    }
                    let minutesText = String(format: "%02d", Int(seconds) / 60)
                    let videoLength =  "\(minutesText):\(secondString)"
                    print(videoLength)

                }
            }

它对我有用。欢呼声。