Sound Effects Revisitied

Ok, so it turns out building a sound effects class around AVAudioPlayer is a bad idea as it’s pretty slow. The game became really choppy as the sound effects were getting fired off and I’m not the world’s best programmer, so I need all the help I can get! :D System Sound Services to the rescue! There are a few drawbacks to using System Sounds like the sounds can’t be over 30 seconds and they must be in WAV, AIF, or CAF format. Not really a big deal for sound effects and I’m still using AVAudioPlayer for the background music.

The reimplemented SoundPlayer class looks much the same as before:


#import "SoundPlayer.h"

@implementation SoundPlayer

@synthesize isFinished;

void audioDidFinish(SystemSoundID sound, void *isFinished);

- (id)init
{
    self = [super init];
    isFinished = true;
    return self;
}

- (void)play:(SystemSoundID)sound
{
    isFinished = false;
    AudioServicesAddSystemSoundCompletion(sound, NULL, NULL, audioDidFinish, &isFinished);
    AudioServicesPlaySystemSound(sound);
}

void audioDidFinish(SystemSoundID sound, void *isFinished)
{
    *(BOOL *)isFinished = true;
    AudioServicesRemoveSystemSoundCompletion(sound);
}

- (void)dealloc
{
    [super dealloc];
}

@end

Something to note: The callback function that fires when the sound finishes is just straight C, not Objective-C. You’ll have to pass any class variables you want to manipulate as the last parameter of the AudioServicesAddSystemSoundCompletion function.

And to initialize the System Sound IDs:


for (i = 0; i < MAX_SOUNDS; i++)
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:[soundPaths objectAtIndex:i] ofType:@"wav"];
    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:filePath], &soundEffects[i]);
}

One last little thing, the System Sounds will play through the phone’s speaker out of the box, but to get them also to play through headphones, you’ll have to add this bit of code. I just stuck it in the viewDidLoad function.


AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:NULL];

Comments are closed.