Reputation: 142
I am seeing this unexpected behavior with pause() function of AVAudioPlayer. When I click on 'Pause' button the audio should actually pause at the current time and resume from it when play() is called. But here, when I hit pause() the audio is paused and when I click on play() the audio is playing from the beginning. pause() is behaving like 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()
}
}
Upvotes: 1
Views: 982
Reputation: 5954
The problem is that you’re creating a new player instance every time play button is clicked. Instead you can create that AVAudioPlayer
instance in advance and only call play() and pause() in your button click handler.
Upvotes: 3