I have a time observer for AVPlayer that works great. Im trying to get it to countdown from the duration of the audio 0.
It works and does count down now I'm just having some trouble with formatting.
if you see the picture below you'll see what i mean. It goes from whole minutes:seconds 3:00, to weird numbers 3:-1 ect.
any ideas what I've done wrong?
heres the code for the timer:
let interval = CMTime(value: 1, timescale: 1)
self.audioPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in
let secondsProgress = CMTimeGetSeconds(progressTime)
let secondsStringProgress = String(format: "%02d", Int((secondsProgress.truncatingRemainder(dividingBy: 60))))
let minuitesStringProgress = String(format: "%02d", Int(secondsProgress) / 60)
//self.countDownLabel.text = "\(minuitesStringProgress):\(secondsStringProgress)"
if let duration = self.audioPlayer?.currentItem!.asset.duration {
let secondsDuration = CMTimeGetSeconds(duration)
let secondsStringDuration = String(format: "%02d", Int((secondsDuration.truncatingRemainder(dividingBy: 60))))
let minuitesStringDuration = String(format: "%02d", Int(secondsDuration) / 60)
let secondsString = String(format: "%02d", Int(secondsStringDuration)! - Int(secondsStringProgress)!)
let minuitesString = String(format: "%02d", Int(minuitesStringDuration)! - Int(minuitesStringProgress)!)
self.countDownLabel.isHidden = false
self.countDownLabel.text = "\(minuitesString):\(secondsString)"
self.horizontalSlider.value = Float(secondsProgress / secondsDuration)
self.circleSlider.value = Float(secondsProgress / secondsDuration)
}
})
I use this function to display formatted date
func getFormatedTime(FromTime timeDuration:Int) -> String {
let minutes = Int(timeDuration) / 60 % 60
let seconds = Int(timeDuration) % 60
let strDuration = String(format:"%02d:%02d", minutes, seconds)
return strDuration
}
use like this
let strDuration = self.getFormatedTime(FromTime: recordingDuration)
or directly like this in addPeriodicTimeObserver
method
recordingDuration = Float(CMTimeGetSeconds((self.playerItem?.asset.duration)!))-Float(CMTimeGetSeconds((self.playerItem?.currentTime())!))
pass it to getFormatedTime
set text of return value
just two lines of code