18

I'm having an issue using AVAudioPlayer where I want to reset a player if it's currently playing and have it play again.

I try the following with no luck:

The sound plays once but then the second time i select the button it stops the sound, the third time starts the sound up again.

//Stop the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    [player stop];
    [player play];
} else {
    NSLog(@"playSound: %@", selectedSound);
    [player play];      
}

I've also tried using player.currentTime = 0 which indicates that would reset the player, that didn't work, I also tried resetting currentTime = 0 and then calling play that didn't work.

//Stop the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    player.currentTime = 0;
    [player play];
} else {
    NSLog(@"playSound: %@", selectedSound);
    [player play];      
}
Dougnukem
  • 14,709
  • 24
  • 89
  • 130

3 Answers3

41

For your situation I would try the following

//Pause the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    [player pause];
}

player.currentTime = 0;
[player play];

If you are going to immediately play the sound again, I would suggest pause instead of stop. Calling stop "Stops playback and undoes the setup needed for playback."

Jonathan Arbogast
  • 9,620
  • 4
  • 35
  • 47
  • 8
    FWIW, I've seen that just setting currentTime to zero is enough. With the method described here, I see the audio refusing to play after doing it a few times in quick succession. – Plumenator Jun 13 '11 at 09:09
4

As indicated, if you want the sound to play again, you should avoid disabling the AVAudioPlayer instance with a stop but rather, just issue a reset of the position where it is playing. So, don't use stop() or pause() but as Plumenator mentioned, just issue .currentTime=0. So in your case, you would simply do:

if (player.isPlaying) { 
   player.currentTime = 0
} else {
   player.play()
}
Justin Ngan
  • 1,050
  • 12
  • 20
  • Since you essentially duplicate Plenumenator's comment, could you expand your answer by adding a reference code sample? – ctietze Jun 20 '19 at 14:08
  • 1
    Thanks, a good suggestion. I've added the block so that it becomes more clear what Plumenator is suggesting :-) Thanks – Justin Ngan Jun 21 '19 at 15:54
1

Swift example:

player.currentTime = 0.0;
Micro
  • 10,303
  • 14
  • 82
  • 120