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


76

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

Answers:


163

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

AVPlayerItem *currentItem = yourAVPlayer.currentItem;

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

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

15
还有一种方便的方法CMTimeGetSeconds来获取NSTimeInterval:NSTimeInterval持续时间= CMTimeGetSeconds(currentItem.duration); NSTimeInterval currentTime = CMTimeGetSeconds(currentItem.currentTime);
slamor

我必须在主队列中设置调用它以使其返回正确的值(或您的avplayer运行于其中的任何队列)。
Pnar Sbi Wer 2015年

1
如何给LABEL这么大的吸引力?
邦德先生

我正在播放url中的歌曲。但是在CMTime持续时间和CMTime currentTime下,我得到0。0值在这里有什么问题?有人知道解决方案吗?
Moxarth's

NSTimeInterval duration3 = CMTimeGetSeconds(currentItem.duration); NSTimeInterval currentTime3 = CMTimeGetSeconds(currentItem.currentTime); NSLog(@“%f和%f”,duration3,currentTime3); self.playbackSlider.value = currentTime3 / duration3;
Genevios

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

14

迅捷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
}

现在,使用先前的计算更新用户界面:

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

播放器上是否有返回毫秒的属性?
bibscy

13

在Swift 4.2中,使用它;

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

我尝试使用AVPlayer.currentTime(),但是没有运气,访问错误
KavyaKavita

currentPlayer.currentItem.currentTime()-您。将。得到正确的时间。
Dolly Vaish19年

这个答案是100%正确的,但是如果您在没有avasset的情况下初始化播放器,则必须使用:* player?.currentItem?.duration。最好使用avasset
Lance Samaria

8

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

    })
}

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

我正在播放url中的歌曲。但是在CMTime持续时间和CMTime currentTime下,我得到0。0值在这里有什么问题?有人知道解决方案吗?
Moxarth

5

迅速:

let currentItem = yourAVPlayer.currentItem

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

3

Swift 5:如果您希望进度条流畅,Timer.scheduledTimer似乎比addPeriodicTimeObserver更好。

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

        Timer.scheduledTimer(withTimeInterval: 1/60, repeats: true) { timer in

            if self.player!.currentItem?.status == .readyToPlay {

                let timeElapsed = CMTimeGetSeconds(self.player!.currentTime())
                let secs = Int(timeElapsed)
                self.currenTime = timeElapsed
                self.currenTimeString = NSString(format: "%02d:%02d", secs/60, secs%60) as String


                print("AudioPlayer TIME UPDATE: \(self.currenTime)    \(self.currenTimeString)")
            }
        }

实际上,您必须从点到点制作平滑的进度条动画-并不是那么容易。你肯定会永远用三聚体(出于任何原因)以1/60 -只需使用CADisplayLink
Fattie

1

Swift 4.2:

let currentItem = yourAVPlayer.currentItem
let duration = currentItem.asset.duration
let currentTime = currentItem.currentTime()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.