AVAudioPlayer stop a sound and play it from the beginning

supersurabbit picture supersurabbit · Oct 2, 2010 · Viewed 9.8k times · Source

I used the AVAudioPlayer to play a 10 sec wav file and it works fine. Now I what to stop the wav at the 4th sec and then play it again from the very 1st sec.

Here is the code I tried:

NSString *ahhhPath = [[NSBundle mainBundle] pathForResource:@"Ahhh" ofType:@"wav"];
AVAudioPlayer *ahhhhhSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:ahhhPath] error:NULL];

[ahhhhhSound stop];
[ahhhhhSound play];

What I get is, the wav stops at the 4th sec but when I run the [XXX play] again, the wav continues to play the 5th sec instead of playing from the beginning.

How could I get this done? Any help will be appreciated.

Answer

DarkDust picture DarkDust · Oct 2, 2010

Apple's AVAudioPlayer class reference says:

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.

So you should be able to restart it with:

[ahhhhhSound stop];
ahhhhhSound.currentTime = 0;
[ahhhhhSound play];