System Sounds

The simplest form of sound is system sound, which is the iOS equivalent of the basic computer “beep.” This is implemented through System Sound Services; you’ll need to import <AudioToolbox/AudioToolbox.h> and link to AudioToolbox.framework. You’ll be calling one of two C functions, which behave very similarly to one another:

AudioServicesPlayAlertSound
Plays a sound and, on an iPhone, may also vibrate the device, depending on the user’s settings.
AudioServicesPlaySystemSound
Plays a short sound of your choice. On an iPhone, there won’t be an accompanying vibration, but you can specifically elect to have this “sound” be a device vibration (by passing kSystemSoundID_Vibrate as the name of the “sound”).

The sound file to be played needs to be an uncompressed AIFF or WAV file (or an Apple CAF file wrapping one of these). To hand the sound to these functions, you’ll need a SystemSoundID, which you obtain by calling AudioServicesCreateSystemSoundID with a CFURLRef (or NSURL) that points to a sound file. In this example, the sound file is in our app bundle:

NSURL* sndurl =
    [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"aif"];
SystemSoundID snd;
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)sndurl, &snd);
AudioServicesPlaySystemSound(snd);

However, there’s a problem with that code: we have failed to exercise proper memory management. We need to call AudioServicesDisposeSystemSoundID to release our SystemSoundID. But when shall we do this? AudioServicesPlaySystemSound ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.