I would like to make a UISlider(scrubber) for my AVPlayer. But since this is not an AVAudioPlayer, it doesn\'t have a built in duration. Any suggestion on how to create the
Swift 5
Put this code inside some function that you desired :
let duration = player.currentItem?.duration.seconds ?? 0
let playDuration = formatTime(seconds: duration) //Duration RESULT
Create a function called: formatTime(seconds: Double)
func formatTime(seconds: Double) -> String {
let result = timeDivider(seconds: seconds)
let hoursString = "\(result.hours)"
var minutesString = "\(result.minutes)"
var secondsString = "\(result.seconds)"
if minutesString.count == 1 {
minutesString = "0\(result.minutes)"
}
if secondsString.count == 1 {
secondsString = "0\(result.seconds)"
}
var time = "\(hoursString):"
if result.hours >= 1 {
time.append("\(minutesString):\(secondsString)")
}
else {
time = "\(minutesString):\(secondsString)"
}
return time
}
Then, another function to translate seconds to hour, minute and second. Since the seconds that by layerLayer.player?.currentItem?.duration.seconds will have long Double, so this is needed to become Human Readable.
func timeDivider(seconds: Double) -> (hours: Int, minutes: Int, seconds: Int) {
guard !(seconds.isNaN || seconds.isInfinite) else {
return (0,0,0)
}
let secs: Int = Int(seconds)
let hours = secs / 3600
let minutes = (secs % 3600) / 60
let seconds = (secs % 3600) % 60
return (hours, minutes, seconds)
}
Hope it's complete your answer.