Swift AVAudioPlayer Restart from Beginning
Asked Answered
K

3

5

I have an AVAudioPlayer stored in a property called "player". When the user clicks a button, it triggers this code:

@IBAction func restartPressed(sender: AnyObject) {
    player.play()
}

The problem is happening when the user clicks the button twice in a row very quickly.

If the sound from the first click is still playing, it seems like the second call is ignored.

Instead, I'd like to either:

a) restart the player from the beginning when the button is clicked a second time; or

b) have two "instances" of the sound playing at the same time.

How would I go about achieving either or both of these options?

Kwa answered 28/1, 2016 at 23:0 Comment(1)
are you using the same button for play and reset?Reproval
P
11

Answering to "either" part (rather than "both") of these options: (a) how to stop and play the sound from beginning:

@IBAction func restartPressed(sender: AnyObject) {
    if player.playing {
        player.pause()
    }
    player.currentTime = 0
    player.play()
}

Regarding (b): from the Language Ref for AVAudioPlayer:

Using an audio player you can:

...

  • Play multiple sounds simultaneously, one sound per audio player, with precise synchronization.

So you'd need two separate players to simultaneously (off-sync) play two separate sounds, even if both players use the same sound. I'd stick with (a).

Poore answered 28/1, 2016 at 23:15 Comment(2)
@MikeG Not according to the ref. docs (see link in answer): "The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off."Poore
you @dfri are correct, .stop() does NOT reset the currentTime to 0, my apologies. stop() does "Calling this method, or allowing a sound to finish playing, undoes the setup performed upon calling the play or prepareToPlay methods." I thought this meant it must reset the resource to the beginning position but I guess notPenniepenniless
T
0

dfri's answer updated for Swift 4

@IBAction func restartPressed(sender: UIButton) {

    if negativePlayer.isPlaying
    {
        negativePlayer.pause()
    }

    negativePlayer.currentTime = 0
    negativePlayer.play()
}
Thacker answered 27/9, 2018 at 8:48 Comment(0)
E
0
player.seek(to: .zero)
player.play()
Eanore answered 21/5, 2022 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.