如何通过AVAudioPlayer当前时间更新播放器滑块手柄当前值



现在我正在使用MSCircularSlider库作为Cocoapod。它的slider.valueslider.currentValue,当我尝试做简单的UISlider(尝试将slider.value等于player.currentTime(时,它运行良好,但是当我尝试在CircularSlider中执行此操作时,手柄不会移动到AVAudioPlayer.currentTime

如何解决?

求求你,帮帮我!

let player = AVAudioPlayer()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CustomCollectionCell
print("tapped")
guard let url = Bundle.main.url(forResource: songsData[indexPath.row].name, withExtension: "mp3") else { return }

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
} catch let error {
print(error.localizedDescription)
}
player.prepareToPlay()
timerLabel.text = String(player.currentTime)
slider.alpha = 1
slider.maximumValue = Float(player.duration)
slider.currentValue = 0.0
Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
player.play()
}
@objc func updateTime(_ timer: Timer) {
let currentTime = player.currentTime
var elapsedTime: TimeInterval = currentTime
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
timerLabel.text = "(strMinutes):(strSeconds)"
timer.invalidate()
self.slider.currentValue = Float(self.player.currentTime)
timer.invalidate()
}

您的updateTime(_:)代码会使计时器失效。(两次!我希望它在 .01 秒后触发一次,然后永远不会再触发,因此您可能不会看到滑块值的明显变化。

摆脱对timer.invalidate()的调用,除非声音播放完毕。

我以前没有使用过那个特定的框架,所以我不确定它是否像你使用它一样有效,但快速浏览一下 README 文件表明你是。

另一方面,Timer对象有点粗糙,最多只能达到 0.02 秒左右的分辨率,因此间隔为 0.01 秒的计时器不太可能经常触发。此外,iOS 设备屏幕上的刷新率为 1/60 秒,因此尝试更频繁地更新屏幕是没有意义的。

如果您真的需要平滑的绘图,在每次屏幕更新时都会更新,您应该使用CADisplayLink计时器查看,但对于这样简单的事情,1/30 秒左右的计时器间隔应该没问题。

最新更新