0

Hello I am using AVPlayer for video streaming.This is what I have done to play.

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

Now I want to add a UISlider to move when the video is playing. So I did in this way.

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)

But when I print the duration this is my output

(lldb) po duration

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

How can I get the duration of this streaming video. Please help me. Thanks

user1960169
  • 3,533
  • 12
  • 39
  • 61
  • I think you can get answer from this: http://stackoverflow.com/questions/40781738/how-to-detect-avplayer-actually-started-to-play-in-swift#comment68786619_40781738 – nynohu Nov 25 '16 at 04:05
  • No I cant get the answer from that. That also has used the same way – user1960169 Nov 25 '16 at 04:33
  • I mean in the answer you need to get AVPlayer status readyToPlay, if you received this status, you can get duration correctly. – nynohu Nov 25 '16 at 04:42

1 Answers1

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)

                }
            }

It works for me. cheers.