使用Swift在进度条上显示AVAudioPlayer的方法如下:
import AVFoundation
guard let audioURL = Bundle.main.url(forResource: "audio", withExtension: "mp3") else {
return
}
do {
let audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
} catch {
print("Failed to load audio file: \(error.localizedDescription)")
}
class ViewController: UIViewController, AVAudioPlayerDelegate {
// ...
func setupAudioPlayer() {
// ...
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
}
func audioPlayerUpdateProgress(_ audioPlayer: AVAudioPlayer) {
let progress = audioPlayer.currentTime / audioPlayer.duration
updateProgressBar(progress)
}
func updateProgressBar(_ progress: Double) {
// 更新进度条的代码
}
// ...
}
class ViewController: UIViewController, AVAudioPlayerDelegate {
// ...
var progressTimer: Timer?
func setupAudioPlayer() {
// ...
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true)
}
@objc func updateProgress() {
audioPlayerUpdateProgress(audioPlayer)
}
// ...
}
class ViewController: UIViewController, AVAudioPlayerDelegate {
// ...
override func viewDidLoad() {
super.viewDidLoad()
setupAudioPlayer()
}
// ...
}
这样,你就可以使用Swift在进度条上显示AVAudioPlayer的播放进度了。记得根据你的实际需求来更新进度条的显示方式和样式。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云