Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple wrapper around Audio Services
/*
- Trivial wrapper around system sound as provided by Audio Services.
- Don’t forget to link against the Audio Toolbox framework.
- Assumes ARC support.
*/
@interface Sound : NSObject
// Path is relative to the resources dir.
- (id) initWithPath: (NSString*) path;
- (void) play;
@end
#import "Sound.h"
#import <AudioToolbox/AudioToolbox.h>
@implementation Sound {
SystemSoundID handle;
}
- (id) initWithPath: (NSString*) path
{
self = [super init];
NSString *const resourceDir = [[NSBundle mainBundle] resourcePath];
NSString *const fullPath = [resourceDir stringByAppendingPathComponent:path];
NSURL *const url = [NSURL fileURLWithPath:fullPath];
OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle);
NSAssert1(errcode == 0, @"Failed to load sound: %@", path);
return self;
}
- (void) dealloc
{
AudioServicesDisposeSystemSoundID(handle);
}
- (void) play
{
AudioServicesPlaySystemSound(handle);
}
@end
@thunderrabbit

This comment has been minimized.

Copy link

thunderrabbit commented Jul 10, 2012

Thanks for this! To use it I had to add #import "Sound.h" to Sound.m

@zoul

This comment has been minimized.

Copy link
Owner Author

zoul commented Jul 10, 2012

Thanks, I missed that. I’ve added the missing #import to the code along with some minor tweaks for ARC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.