Reputation: 411
I'm playing a song using AVAudioPlayer
. I need a progress bar to show the progress of the song.
My issue is that the progress bar's progress isn't working properly. Within 2-3 seconds, it finishes its progress.
func playMusic() {
do {
player = try AVAudioPlayer(contentsOf: (currentSong?.mediaURL)!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
updater = CADisplayLink(target: self, selector: #selector(self.musicProgress))
updater.frameInterval = 1
updater.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
playButton.setImage(UIImage.init(named: "pause"), for: .normal)
} catch let error as NSError {
print(error.description)
}
}
@objc func musicProgress() {
let normalizedTime = Float(self.player?.currentTime as! Double * 100.0 / (self.player?.duration as! Double) )
self.progressMusic.progress = normalizedTime
}
Upvotes: 1
Views: 4992
Reputation: 6992
The issue is here:
let normalizedTime = Float(self.player?.currentTime as! Double * 100.0 / (self.player?.duration as! Double) )
With this you will get a value between 0.0
and 100.0
, but according to UIProgressView
documentation, progress
must be between 0.0
and 1.0
. Try
let normalizedTime = Float(self.player?.currentTime as! Double / (self.player?.duration as! Double) )
Upvotes: 2