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

问题描述 投票:0回答:10

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

ios avplayer
10个回答
179
投票

您可以使用

currentItem
属性访问当前播放的项目:

AVPlayerItem *currentItem = yourAVPlayer.currentItem;

然后就可以轻松获取所请求的时间值了

CMTime duration = currentItem.duration; //total time
CMTime currentTime = currentItem.currentTime; //playing time

斯威夫特 5

if let currentItem = player.currentItem {
    let duration = CMTimeGetSeconds(currentItem.duration)
    let currentTime = CMTimeGetSeconds(currentItem.currentTime())

    print("Duration: \(duration) s")
    print("Current time: \(currentTime) s")
}

24
投票
_audioPlayer = [self playerWithAudio:_audio];
_observer =
[_audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 2)
                                           queue:dispatch_get_main_queue()
                                      usingBlock:^(CMTime time)
                                      {
                                          _progress = CMTimeGetSeconds(time);
                                      }];

22
投票

斯威夫特3

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

您可以通过访问

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)
}

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

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)
    }
}

16
投票

斯威夫特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)"

    })
}

16
投票

对于 Swift 4.2,使用这个;

let currentPlayer = AVPlayer()
if let currentItem = currentPlayer.currentItem {
    let duration = currentItem.asset.duration
}
let currentTime = currentPlayer.currentTime()

6
投票

斯威夫特 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)")
            }
        }
    }
}

5
投票
     AVPlayerItem *currentItem = player.currentItem;
     NSTimeInterval currentTime = CMTimeGetSeconds(currentItem.currentTime);
     NSLog(@" Capturing Time :%f ",currentTime);

5
投票

斯威夫特:

let currentItem = yourAVPlayer.currentItem

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

1
投票

斯威夫特 4.2:

let currentItem = yourAVPlayer.currentItem
let duration = currentItem.asset.duration
let currentTime = currentItem.currentTime()

1
投票

快速 5+

您可以直接查询播放器以找到正在播放的AVPlayerItem的当前时间。 时间存储在 CMTime 结构中,以便于转换为各种尺度,例如十分之一秒、百分之一秒等 在大多数情况下,我们需要以秒为单位表示时间,因此下面将向您展示您想要的

let currentTimeInSecs = CMTimeGetSeconds(player.currentTime())
© www.soinside.com 2019 - 2024. All rights reserved.