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

Vol*_*da2 67 ios avplayer

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

Bar*_*ski 149

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

AVPlayerItem *currentItem = yourAVPlayer.currentItem;
Run Code Online (Sandbox Code Playgroud)

然后,您可以轻松获得所需的时间值

CMTime duration = currentItem.duration; //total time
CMTime currentTime = currentItem.currentTime; //playing time
Run Code Online (Sandbox Code Playgroud)

  • 还有方便的方法CMTimeGetSeconds来获取NSTimeInterval:NSTimeInterval duration = CMTimeGetSeconds(currentItem.duration); NSTimeInterval currentTime = CMTimeGetSeconds(currentItem.currentTime); (14认同)

com*_*tos 22

_audioPlayer = [self playerWithAudio:_audio];
_observer =
[_audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 2)
                                           queue:dispatch_get_main_queue()
                                      usingBlock:^(CMTime time)
                                      {
                                          _progress = CMTimeGetSeconds(time);
                                      }];
Run Code Online (Sandbox Code Playgroud)


Bra*_*n A 12

斯威夫特3

let currentTime:Double = player.currentItem.currentTime().seconds
Run Code Online (Sandbox Code Playgroud)

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

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

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

现在,使用先前的计算更新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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Kem*_*nak 10

使用Swift 4.2,使用此;

let currentPlayer = AVPlayer()
if let currentItem = currentPlayer.currentItem {
    let duration = currentItem.asset.duration
}
let currentTime = currentPlayer.currentTime()
Run Code Online (Sandbox Code Playgroud)


小智 10

斯威夫特 4

    self.playerItem = AVPlayerItem(url: videoUrl!)
    self.player = AVPlayer(playerItem: self.playerItem)

    self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main, using: { (time) in
        if self.player!.currentItem?.status == .readyToPlay {
            let currentTime = CMTimeGetSeconds(self.player!.currentTime())

            let secs = Int(currentTime)
            self.timeLabel.text = NSString(format: "%02d:%02d", secs/60, secs%60) as String//"\(secs/60):\(secs%60)"

    })
}
Run Code Online (Sandbox Code Playgroud)


Thy*_*ius 7

Swift 5:如果你想要一个平滑的进度条,Timer.scheduledTimer 似乎比 addPeriodicTimeObserver 更好

var currenTime = 0.0
var currenTimeString = "00:00"

func showAudioTime()
{
    Timer.scheduledTimer(withTimeInterval: 1/60, repeats: true) { timer in
        guard let player = self.player else { return }
        DispatchQueue.main.async
        {
            if player.currentItem?.status == .readyToPlay {
                let timeElapsed = CMTimeGetSeconds(player.currentTime())
                let secs = Int(timeElapsed)
                self.currenTime = timeElapsed
                self.currenTimeString = NSString(format: "%02d:%02d", secs/60, secs%60) as String
                
                self.currentPlaybackTimeLabel.text = self.currenTimeString
                
                print("AudioPlayer TIME UPDATE: \(self.currenTime)    \(self.currenTimeString)")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ath*_*Raj 5

     AVPlayerItem *currentItem = player.currentItem;
     NSTimeInterval currentTime = CMTimeGetSeconds(currentItem.currentTime);
     NSLog(@" Capturing Time :%f ",currentTime);
Run Code Online (Sandbox Code Playgroud)


Uni*_*kat 5

迅速:

let currentItem = yourAVPlayer.currentItem

let duration = currentItem.asset.duration
var currentTime = currentItem.asset.currentTime
Run Code Online (Sandbox Code Playgroud)