AVAudioPlayer暂停()不像预期的那样运行
问题描述:
我看到这个意外的行为,带有AVAudioPlayer的暂停()函数。当我点击'暂停'按钮时,音频实际上应该在当前时间暂停,并在调用play()时从其中恢复。但在这里,当我点击暂停()时音频暂停,当我点击play()时,音频从头开始播放。暂停()的行为就像stop()。AVAudioPlayer暂停()不像预期的那样运行
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()
}
}
答
问题是,您每次单击播放按钮时都会创建一个新播放器实例。相反,您可以提前创建该实例并仅在按钮点击处理程序中调用play()和pause()。