如何使用AVAudioPlayer播放音效?

时间:2014-08-20 00:00:14

标签: ios objective-c cocos2d-iphone avaudioplayer

每当我播放AVAudio剪辑时,剪辑会播放,然后片刻之后会崩溃。我无法弄清楚为什么。当它崩溃时,它不会在日志中给我任何东西。这是我的代码。我还导入了AVFoundation/AVFoundation.hAudioToolbox/AudioToolbox.h

-(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];
}

1 个答案:

答案 0 :(得分:0)

以下是答案:

由于您使用的是cocos2d,如果您使用v3.x或OALSimpleAudio,则可以使用SimpleAudioEngine,如果您使用的是v3.x:

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

当你在场景结束时完成它时:

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

对于v3,等价物是:

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