views:

521

answers:

2

Does anyone have a snippet that uses the AudioToolBox framework that can be used to play a short sound? I would be grateful if you shared it with me and the rest of the community. Everywhere else I have looked doesn't seem to be too clear with their code.

Thanks!

+2  A: 

Here is an easy example using the AVAudioPlayer:

-(void)PlayClick
{
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                               pathForResource:@"click"
                                               ofType:@"caf"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];
}

This assumes a file called "click.caf" available in the main bundle. As I play this sound a lot, I actually keep it around to play it later instead of releasing it.

Nathan S.
Thank you so much!! I will certainly keep this around for future use.
esqew
A: 

I wrote a simple Objective-C wrapper around AudioServicesPlaySystemSound and friends:

#import <AudioToolbox/AudioToolbox.h>

/*
    Trivial wrapper around system sound as provided
    by Audio Services. Don’t forget to add the Audio
    Toolbox framework.
*/

@interface Sound : NSObject
{
    SystemSoundID handle;
}

// Path is relative to the resources dir.
- (id) initWithPath: (NSString*) path;
- (void) play;

@end

@implementation Sound

- (id) initWithPath: (NSString*) path
{
    [super init];
    NSString *resourceDir = [[NSBundle mainBundle] resourcePath];
    NSString *fullPath = [resourceDir stringByAppendingPathComponent:path];
    NSURL *url = [NSURL fileURLWithPath:fullPath];

    OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle);
    NSAssert1(errcode == 0, @"Failed to load sound: %@", path);
    return self;
}

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

- (void) play
{
    AudioServicesPlaySystemSound(handle);
}

@end

Lives here. For other sound options see this question.

zoul