简体   繁体   中英

AVAudioPlayer pause() not behaving as expected

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()

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM