如何在AVPlayer中获得当前播放时间和总播放时间?

在AVPlayer中可以播放时间和总播放时间吗? 如果是,我该怎么做?

您可以使用currentItem属性来访问当前播放的项目:

 AVPlayerItem *currentItem = yourAVPlayer.currentItem; 

那么你可以很容易地得到所需的时间值

 CMTime duration = currentItem.duration; //total time CMTime currentTime = currentItem.currentTime; //playing time 
 _audioPlayer = [self playerWithAudio:_audio]; _observer = [_audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 2) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) { _progress = CMTimeGetSeconds(time); }]; 

用Swift 2.0,使用这个;

 let currentPlayerItem = AVPlayer.currentItem let duration = currentPlayerItem?.asset.duration var currentTime = AVPlayer.currentTime() 
  AVPlayerItem *currentItem = player.currentItem; NSTimeInterval currentTime = CMTimeGetSeconds(currentItem.currentTime); NSLog(@" Capturing Time :%f ",currentTime); 

Swift 3

 let currentTime:Double = player.currentItem.currentTime().seconds 

您可以通过访问currentTime()seconds属性来获取当前时间的seconds 。 这将返回一个Double ,表示秒数。 然后你可以使用这个值来构build一个可读的时间来呈现给你的用户。

首先,包含一个方法来返回您将显示给用户的H:mm:ss的时间variables:

 func getHoursMinutesSecondsFrom(seconds: Double) -> (hours: Int, minutes: Int, seconds: Int) { let secs = Int(seconds) let hours = secs / 3600 let minutes = (secs % 3600) / 60 let seconds = (secs % 3600) % 60 return (hours, minutes, seconds) } 

接下来,将上面检索到的值转换为可读的string的方法:

 func formatTimeFor(seconds: Double) -> String { let result = getHoursMinutesSecondsFrom(seconds: seconds) let hoursString = "\(result.hours)" var minutesString = "\(result.minutes)" if minutesString.characters.count == 1 { minutesString = "0\(result.minutes)" } var secondsString = "\(result.seconds)" if secondsString.characters.count == 1 { secondsString = "0\(result.seconds)" } var time = "\(hoursString):" if result.hours >= 1 { time.append("\(minutesString):\(secondsString)") } else { time = "\(minutesString):\(secondsString)" } return time } 

现在,用以前的计算来更新UI:

 func updateTime() { // Access current item if let currentItem = player.currentItem { // Get the current time in seconds let playhead = currentItem.currentTime().seconds let duration = currentItem.duration.seconds // Format seconds for human readable string playheadLabel.text = formatTimeFor(seconds: playhead) durationLabel.text = formatTimeFor(seconds: duration) } } 

迅速:

 let currentItem = yourAVPlayer.currentItem let duration = currentItem.asset.duration var currentTime = currentItem.asset.currentTime