Bill Bill - 1 year ago 43
Objective-C Question

How to debug why a sound won't play via AVAudioPlayer?

I have a simple iPhone app with several sounds already playing. However, one in particularly won't. The code block I've hacked up is:

NSString *soundPath2 = [[NSBundle mainBundle] pathForResource:@"gameover" ofType:@"wav"];
NSURL *soundFileURL2 = [NSURL fileURLWithPath:soundPath2];
NSError *err;
AVAudioPlayer *sound2 = [[[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL2 error:&err] autorelease];
NSLog(@"Error: %@", [err description]);
NSLog(@"Duration: %f ", [sound2 duration]);
BOOL b = [sound2 play];
NSLog(@"Play Bool: %d", b);

The console shows the error is null, the boolean returns true, and even the duration is correct! Yet, play does nothing. If I change "gameover" to another sound (a simple beep), all is fine.

While it would be great to get it play, I'm also struggling to understand what error conditions, etc. I can check to 1) know it failed and 2) why.

The sound is question is available at

Answer Source

The problem is that you shouldn't be autoreleasing the AVAudioPlayer. The play method happens asynchronously and if the player gets autoreleased then nothing is holding on to it and it will just die.

You should release your audio player once the player is done playing in the delegate:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)audioPlayer successfully:(BOOL)flag