An Objective-C wrapper for AudioServicesPlaySystemSound

In Tallymander 2.0 I use a handful of sound effects to provide user feedback. I thought that the amount of code I had to write every time I wanted to play back a sound was a bit cumbersome so I wrote this wrapper around the AudioToolbox C functions I was using.

DCSoundServices.h:

#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
 
@interface DCSoundServices : NSObject {
 
}
 
+ (void)playSoundWithName:(NSString *)fileName type:(NSString *)fileExtension;
+ (void)vibrateDevice;
 
@end

DCSoundServices.m:

#import "DCSoundServices.h"
 
@implementation DCSoundServices
 
+ (void)playSoundWithName:(NSString *)fileName type:(NSString *)fileExtension
{
 
	CFStringRef cfFileName = (CFStringRef) fileName;
	CFStringRef cfFileExtension = (CFStringRef) fileExtension;
 
	CFBundleRef mainBundle;
	mainBundle = CFBundleGetMainBundle ();
 
	CFURLRef soundURLRef  = CFBundleCopyResourceURL (mainBundle, cfFileName, cfFileExtension, NULL);
 
	SystemSoundID soundID;
 
	AudioServicesCreateSystemSoundID (soundURLRef, &soundID);
 
 
	AudioServicesPlaySystemSound (soundID);
 
	CFRelease(soundURLRef);
 
}
 
+ (void)vibrateDevice
{
	AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
 
@end

Assuming you’ve got a sound file named click.aif in your application bundle, you can play a sound in just one line of code:

[DCSoundServices playSoundWithName:@"click" type:@"aif"]

Or, vibrate the device:

[DCSoundServices vibrateDevice]

Much tidier than having to import AudioToolbox into every UI that ever plays back a sound.

Comments

  1. Franklyn June 10th

    Comment Arrow

    Many thanks! Being new to all this, I find even the Apple docs hard to understand, it’s loads better to have decent example code.


Add Yours

  • Author Avatar

    YOU


Comment Arrow