1

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
}
Artem Garmash
  • 154
  • 10
Digvijaysinh Gida
  • 381
  • 1
  • 7
  • 20

1 Answers1

2

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) )
mag_zbc
  • 6,801
  • 14
  • 40
  • 62