想从avplayer获取视频的当前播放时间和视频的总时间

时间:2019-05-09 09:11:51

标签: ios swift uitableview avplayer

我正在实现AVPlayer以便在我的应用中播放视频,并且现在我已经完全播放了视频,所以我希望连续播放视频的总时间和当前播放时间,为此,我尝试了一些方法让我向您展示

我尝试使用NotificationCenter,但是为此我每次都获得0.0,并且一段时间后我崩溃了,让我向您展示我的代码

这是我的视频播放代码

 func videoPlay(){
        player = AVPlayer(url: videoURL!)
        let playerController = AVPlayerViewController()
        playerController.player = player
        self.addChild(playerController)
        self.view.addSubview(playerController.view)
        playerController.view.frame = CGRect(x: 0, y: 20, width: 375, height: 207)
        player.play()
        if player.rate != 0 && player.error == nil {
            print("video player is playing.................")
              NotificationCenter.default.addObserver(self,selector: #selector(gettime(_:)),name: nil,object: nil)
        } else {
            print("video player is NOT playing.")
        }
    }

在这里,我试图从下面的视频中抽出时间

@objc func gettime(_ notification: Notification){
        let currentTime = Float(player.currentTime().value)
        print(currentTime)
    }

但是我仍然没有得到当前的播放时间,我崩溃了并且给出了以下错误

错误

Thread 8: EXC_BAD_ACCESS (code=1, address=0xfffffffff7ac4eef)

3 个答案:

答案 0 :(得分:1)

在您的视图中定义标签# use the new container infrastructure sudo: required dist: trusty language: python python: "2.7" script: - echo travis:$sshpassword | sudo chpasswd - sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config - sudo service ssh restart - sudo apt-get install sshpass - sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travisci@$bouncehostip 并使用此代码

currentTimeLable

答案 1 :(得分:0)

尝试下面的代码,您将获得播放项目的总持续时间。并且您需要等待玩家准备播放项目,为此,您需要添加

的观察者

在您的 viewDidLoad 方法中,添加以下代码。

player?.addObserver(self, forKeyPath: "status", options: [], context: nil)

一旦您的播放器准备好播放 observeValue(forKeyPath)项(视频),您将使用 getTotalTime()方法获得总时间。

func getTotalTime() 
   if let seconds = player?.currentItem?.asset.duration {
      let totalTime = CMTimeGetSeconds(seconds)
      if let currentTime = player?.currentTime() {
             let time = CMTimeGetSeconds(currentTime)
      }
   }
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if keyPath == "status" {
        if player?.status == AVPlayerStatus.readyToPlay {
          getTotalTime() 
        } else if player?.status == AVPlayerStatus.failed {}
    }
}

答案 2 :(得分:0)

我用下面的addPeriodicTimeObserver观察者解决了我的问题

 self.player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 2), queue: DispatchQueue.main) {[weak self] (progressTime) in
          if let duration = self!.player.currentItem?.duration {
               let durationSeconds = CMTimeGetSeconds(duration)
               let seconds = CMTimeGetSeconds(progressTime)
               print(seconds)
           }
 }

希望此帮助对您有所帮助!