Alan_s Alan_s - 1 year ago 113
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];

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download