Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resume sound in AVAudioPlayer with swift

I am trying to play a clip of sound that can be paused, resumed or stopped. My pause button works, and the action function for this button is shown below. However I cannot get my resume function to work. When I press the resume button no audio is played. I have read around online and the only tips I can find are to use the prepareToPlay() function and to set shortStartTimeDelay to a value greater than 0.0. I have tried both of these to no avail.

timeAtPause is a global variable of type NSTimeInterval

The action function for the pause button is as follows:

@IBAction func pauseAllAudio(sender: UIButton) { timeAtPause = audioPlayer.currentTime audioPlayer.pause() }

The action function for the resume button is as follows:

@IBAction func resumeAllAudio(sender: UIButton) {
    let shortStartDelay = 0.01
    audioPlayer.prepareToPlay()
    audioPlayer.playAtTime(timeAtPause + shortStartDelay)
}

Any tips on how to resume the audio would be really appreciated. Thank you for your time.

like image 328
JungleBook Avatar asked Feb 13 '16 11:02

JungleBook


2 Answers

You should not use playAtTime() to resume the AVAudioPlayer, as documentation states:

Plays a sound asynchronously, starting at a specified point in the audio output device’s timeline.

and

Use this method to precisely synchronize the playback of two or more AVAudioPlayer objects.

And, even if you use it, it should be used in conjunction with deviceCurrentTime plus the time in seconds to have the delay. In one word, it's not meant to be used to resume the paused player. Instead, just use play() to resume the playback.

like image 69
Fahri Azimov Avatar answered Oct 05 '22 07:10

Fahri Azimov


You probably did what I did. Upon calling my play() function, I created a new player every time:

// The Wrong Way
@IBAction func playAction(sender: AnyObject) {
    // do and catch omitted for brevity
    player = try AVAudioPlayer(contentsOf: goodURL)
    player.play()
}

However this should be done at some other initialization time, such as when you have the user choose the file to play. Or, if you're hard-coding the file to play, you could initialize at an earlier time, such as viewDidLoad().

Then, once your AVAudioPlayer is initialized, you can call .play() and pause() on it and they will work correctly. And .play() will resume after a pause.

like image 20
Rob Avatar answered Oct 05 '22 06:10

Rob