AVAudioPlayer 如何使用 swift 显示进度条?

How to AVAudioPlayer with progress bar show using swift?

我正在使用 AVAudioPlayer 播放歌曲。我需要一个进度条来显示歌曲的进度。

我的问题是进度条的进度显示不正常。在 2-3 秒内,它完成了它的进度。

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
}

问题在这里:

let normalizedTime = Float(self.player?.currentTime as! Double * 100.0 / (self.player?.duration as! Double) )

有了这个你会得到一个介于 0.0100.0 之间的值,但是根据 UIProgressView 文档,progress 必须介于 0.01.0。尝试

let normalizedTime = Float(self.player?.currentTime as! Double / (self.player?.duration as! Double) )