Alan_s Alan_s - 3 months ago 21x
iOS Question

How to use AVAudioPlayer to play sound effects?

Whenever I play my

clip, the clip plays, and then it crashes a moment later. I can't figure out why. When it crashes, it doesn't give me anything in the log. Here is my code. I've also imported

-(void)soundEffect {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"BlastWAV" ofType:@"wav"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];

NSError *error = nil;

avSound = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[avSound prepareToPlay];

[avSound play];


Here is the answer:

Since you are using cocos2d you can use the SimpleAudioEngine if you are using v2.x or OALSimpleAudio if you are using v3.x like so:

[[SimpleAudioEngine sharedEngine] preloadEffect:@"sound.caf"];
[[SimpleAudioEngine sharedEngine] playEffect:@"sound.caf"];

and when you are done with it at the end of the scene:

[[SimpleAudioEngine sharedEngine] unloadEffect:@"sound.caf"];

For v3 the equivalent is:

[[OALSimpleAudio sharedInstance] preloadEffect:@"sound.caf"];
[[OALSimpleAudio sharedInstance] playEffect:@"sound.caf" loop:NO];
[[OALSimpleAudio sharedInstance] unloadAllEffects];