ios - 如何使用 swift 显示带有进度条的 AVAudioPlayer?

标签 ios swift avaudioplayer uiprogressbar

我正在使用 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) )

关于ios - 如何使用 swift 显示带有进度条的 AVAudioPlayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54347747/

相关文章:

ios - ios 7中未声明的选择器警告

arrays - 如何为数组进行切换?

objective-c - 对 objective-c 有帮助吗?我的应用程序不断崩溃?

swift - 使用 MusicSequence 初始化 AVMIDIPlayer

ios - 在 iOS 上开始在后台播放声音?

ios - 滑动手势不起作用

ios - 删除了 XIB,应用程序有时会崩溃

ios - 如何使用 SRWebsocket 检查网络套接字是否处于事件状态

ios - ServiceStack Swift 插件是否在 Xcode 6.2 上运行?

swift - 快速重载 'class func'