AVPlayer返回纳米视频

时间:2018-03-09 07:16:44

标签: ios avplayer swift4

我正在尝试使用以下代码在avplayer上播放视频...但是没有得到任何结果,因为它显示持续时间为nan。

func setUpPlayer(fileURL:URL){
        let playerItem:AVPlayerItem = AVPlayerItem(url: fileURL)
        player = AVPlayer(playerItem: playerItem)
        let playerLayer=AVPlayerLayer(player: player!)
        playerLayer.frame=CGRect(x:self.videoContainer.frame.origin.x, y:self.videoContainer.frame.origin.y+20, width:self.videoContainer.frame.size.width, height:self.videoContainer.frame.size.height-40)
        player?.addObserver(
            self, forKeyPath:"currentItem", options:.initial, context:nil)

        self.view.layer.addSublayer(playerLayer)


        rangeSlider.setVideoURL(videoURL:fileURL)
        rangeSlider.delegate = self

        self.endTime = CMTimeGetSeconds((player?.currentItem?.duration)!)


       let timeInterval: CMTime = CMTimeMakeWithSeconds(0.01, 100)

//        let asset:AVURLAsset = AVURLAsset.init(url:videoURL)
//        let videoDuration:CMTime = asset.duration;
//
//
//        let timeInterval: CMTime = CMTimeMakeWithSeconds(videoDuration,100)
            //CMTimeGetSeconds(videoDuration)

        timeObserver = player?.addPeriodicTimeObserver(forInterval: timeInterval,
                                                        queue: DispatchQueue.main) { (elapsedTime: CMTime) -> Void in

                                                            self.observeTime(elapsedTime: elapsedTime)

            } as AnyObject!

    }

我是第一次这样做。请给出一些解决方案来解决这个问题。提前谢谢!

1 个答案:

答案 0 :(得分:0)

你错过了在你的代码中写“player.play()”

let timeRange = self.avPlayer.currentItem.loadedTimeRanges[0].CMTimeRangeValue
let duration = CMTimeGetSeconds(timeRange.duration)

试试这个会有所帮助