George Johnston
George Johnston

Reputation: 32278

Waiting until another sound is finished before playing a new one

I am developing an iPhone application that plays sounds. I do not want interrupt or play another sound, if a sound is already playing, regardless of where it was "spawned" from to play. My code is as follows:

if(distance <= 10)
{
   NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"];
   SystemSoundID soundID;
   AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
   AudioServicesPlaySystemSound(soundID); 
}

Simply, I do not want to play a new sound if one is already playing.

I do not want to queue another sound to play if one is already playing.

Is this possible?

Upvotes: 1

Views: 2684

Answers (1)

Jiva DeVoe
Jiva DeVoe

Reputation: 1348

I suggest you use the AVAudioPlayer API rather than AudioServicesPlaySystemSound. It has a delegate which you can use, which defines a method -audioPlayerDidFinishPlaying:successfully: which will tell you when your sound finishes playing. The AVPlayer class also has a -playing method which you can check to see if a sound is currently playing.

So, in other words, do this instead:

NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundPath error:&error];
if(!player)
   [self doSomethingWithError:error];
[player setDelegate:self];
[player play];

Upvotes: 4

Related Questions