AVAudioPlayer pause() 未按预期运行
AVAudioPlayer pause() not behaving as expected
我在 AVAudioPlayer 的 pause() 函数中看到了这种意外行为。当我点击 'Pause' 按钮时,音频实际上应该在当前时间暂停并在调用 play() 时从它恢复。但是在这里,当我点击 pause() 时,音频暂停,当我点击 play() 时,音频从头开始播放。 pause() 的行为类似于 stop()。
var player: AVAudioPlayer = AVAudioPlayer()
@IBAction func PlayPauseAudioButton(_ sender: UIButton) {
if sender.currentImage == #imageLiteral(resourceName: "play-btn") {
sender.setImage(#imageLiteral(resourceName: "pause-btn"), for: .normal)
do {
let audioPath = Bundle.main.path(forResource: "aug-ps-raj", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
} catch {
// Catch the error
}
player.play()
} else {
sender.setImage(#imageLiteral(resourceName: "play-btn"), for: .normal)
player.pause()
}
}
问题是每次单击播放按钮时您都会创建一个新的播放器实例。相反,您可以提前创建 AVAudioPlayer
实例,并仅在按钮单击处理程序中调用 play() 和 pause()。
我在 AVAudioPlayer 的 pause() 函数中看到了这种意外行为。当我点击 'Pause' 按钮时,音频实际上应该在当前时间暂停并在调用 play() 时从它恢复。但是在这里,当我点击 pause() 时,音频暂停,当我点击 play() 时,音频从头开始播放。 pause() 的行为类似于 stop()。
var player: AVAudioPlayer = AVAudioPlayer()
@IBAction func PlayPauseAudioButton(_ sender: UIButton) {
if sender.currentImage == #imageLiteral(resourceName: "play-btn") {
sender.setImage(#imageLiteral(resourceName: "pause-btn"), for: .normal)
do {
let audioPath = Bundle.main.path(forResource: "aug-ps-raj", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
} catch {
// Catch the error
}
player.play()
} else {
sender.setImage(#imageLiteral(resourceName: "play-btn"), for: .normal)
player.pause()
}
}
问题是每次单击播放按钮时您都会创建一个新的播放器实例。相反,您可以提前创建 AVAudioPlayer
实例,并仅在按钮单击处理程序中调用 play() 和 pause()。