Reputation: 1465
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?
Upvotes: 6
Views: 6602
Reputation: 1487
dfri's answer updated for Swift 4
@IBAction func restartPressed(sender: UIButton) {
if negativePlayer.isPlaying
{
negativePlayer.pause()
}
negativePlayer.currentTime = 0
negativePlayer.play()
}
Upvotes: 0
Reputation: 73206
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).
Upvotes: 12