我有AVPlayer,当我倒回音频文件时,当前时间比总文件持续时间长。谁知道问题出在哪里,为什么当前时间不对?
@objc func updateProgressBar(){
guard let value = AppDelegate.avPlayer.currentItem?.currentTime().seconds else { return }
let time = Func.getHoursMinutesSecondsFrom(seconds: value)
DispatchQueue.main.async {
self.startTime.text = time.fullTime
}
}
func durationAudio(){
// расчитывает время аудиозвука
guard let duration = AppDelegate.avPlayer.currentItem?.asset.duration else { return }
let time = Func.getHoursMinutesSecondsFrom(seconds: CMTimeGetSeconds(duration))
DispatchQueue.main.async {
self.endTime.text = time.fullTime
}
}
转换为小时、分钟、秒
static func getHoursMinutesSecondsFrom(seconds: Double) -> (hours: Int, minutes: Int, seconds: Int, fullTime:String) {
let secs = Int(seconds)
let hours = secs / 3600
let minutes = (secs % 3600) / 60
let seconds = (secs % 3600) % 60
let duration:String!
if hours != 0 {
duration = String(format:"%02d:%02d:%02d", hours, minutes, seconds)
} else {
duration = String(format:"%02d:%02d", minutes, seconds)
}
return (hours, minutes, seconds, duration)
}
快退音频
func seekTo(completion:Bool){
let duration = CMTimeGetSeconds(AppDelegate.avPlayer.currentItem!.asset.duration)
let value = self.sliderSong.value
let durationToSeek = Float(duration) * value
let timeScale = AppDelegate.avPlayer.currentItem!.duration.timescale
AppDelegate.avPlayer.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek), preferredTimescale: timeScale), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) { [weak self](bool) in
guard completion else { return }
self?.seeking = false
}
}
您可以使用以下代码顺利寻找玩家:
@objc func sliderValueChanged(_ sender: UISlider) {
self.seekAudio(to: sender.value) // seek Player
}
func seekAudio(to newValue: Float) {
guard let player = self.player,
let currentItem = player.currentItem,
currentItem.status == .readyToPlay else {
print("Player or current item not ready.")
return
}
let duration = currentItem.duration.seconds
guard duration.isFinite else {
return
}
let newPosition = duration * Double(newValue)
let seekTime = CMTime(seconds: newPosition, preferredTimescale: 600)
player.seek(to: seekTime, toleranceBefore: .zero, toleranceAfter: .zero) { completed in
if completed {
//print("Seek operation completed successfully.")
} else {
//print("Seek operation was not completed successfully.")
}
}
}