簡體   English   中英

如何使用 swift 顯示帶有進度條的 AVAudioPlayer?

[英]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) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM