我看到了AVAudioPlayer的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()
}
}
答案 0 :(得分:2)
问题是每次点击播放按钮时都会创建一个新的播放器实例。相反,您可以提前创建AVAudioPlayer
实例,只在按钮单击处理程序中调用play()和pause()。