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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8181533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:27:45  来源:igfitidea点击:

How do I get current playing time and total play time in AVPlayer?

iosavplayer

提问by Voloda2

Is it possible get playing time and total play time in AVPlayer? If yes, how can I do this?

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

回答by Bartosz Ciechanowski

You can access currently played item by using currentItemproperty:

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

AVPlayerItem *currentItem = yourAVPlayer.currentItem;

Then you can easily get the requested time values

然后您可以轻松获取请求的时间值

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

回答by comonitos

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

回答by Brandon A

Swift 3

斯威夫特 3

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

You can get the seconds of your current time by accessing the secondsproperty of the currentTime(). This will return a Doublethat represents the seconds in time. Then you can use this value to construct a readable time to present to your user.

您可以通过访问了解您的当前时间的秒数seconds的财产currentTime()。这将返回一个Double代表时间的秒数。然后你可以使用这个值来构建一个可读的时间来呈现给你的用户。

First, include a method to return the time variables for H:mm:ssthat you will display to the user:

首先,包含一个方法来返回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)
}

Next, a method that will convert the values you retrieved above into a readable 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
}

Now, update the UI with the previous calculations:

现在,使用之前的计算更新 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)
    }
}

回答by Kemal Can Kaynak

With Swift 4.2, use this;

使用 Swift 4.2,使用这个;

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

回答by Athul Raj

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

回答by Unis Barakat

Swift:

迅速:

let currentItem = yourAVPlayer.currentItem

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

回答by xuzepei

Swift 4

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

    })
}

回答by Thyselius

Swift 5: Timer.scheduledTimer seems better than addPeriodicTimeObserver if you want to have a smooth progress bar

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

回答by Matthijs

Swift 4.2:

斯威夫特 4.2:

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