6.3. Audio Services

For simple, unmixed sounds, the Audio Toolbox framework provides a C-style audio service. You can play simple sounds using the AudioServicesPlaySystemSound function. A few rules apply to playing simple sounds. Sounds must be less than 30 seconds in length, and must be PCM or IMA4 formats. The file must also be stored in a .caf, .aif, or .wav file. Simple sounds cannot be played from memory, but only disk files. If you're developing on version 2.2 or greater of the SDK, you may want to use the AVFoundation framework in lieu of audio services.

In addition to the restrictions on simple sounds, you'll have very little control over the manner in which the sound is played. When played, the sound will be triggered immediately and at the current sound level set by the phone's user. You won't be able to loop sounds or manage stereo either. You can however, invoke a callback function when the sound is finished playing, so that you can clean up your sound objects and notify your application.

Example 6-8 illustrates the audio service calls to play a sound file named sample.wav.

Example 6-8. Audio services example (SoundExample.m)
#include <AudioToolbox/AudioToolbox.h>
#include <CoreFoundation/CoreFoundation.h>

// When the sound is finished playing, this function is called
static void SoundFinished (SystemSoundID soundID, void *sample)
    /* I'm all finished playing, so free up resources */


// Main loop
int main()
    /* System Sound ID, which we'll register to play our sound as */
    SystemSoundID soundID;
    NSURL *sample = [ [ NSURL alloc ] initWithString: @"sample.wav" ];

    OSStatus err = AudioServicesCreateSystemSoundID (sample, &soundID);
    if (err) {
        NSLog(@"Error occurred assigning system sound!");

    /* Add sound-completion callback */
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL,
        SoundFinished, sample);

    /* Play it! */
    return 0;


6.3.1. What's Going On

The audio services example works like this:

  1. The application's main function is invoked when executed.

  2. An NSURL object is created, pointing to the path of the sound file.

  3. The AudioServicesCreateSystemSoundID function is called to create a system sound out of the sound file.

  4. The sound completion callback function, SoundFinished, is registered as the callback.

  5. The system sound identifier assigned to our sound is instructed to play by calling AudioervicesPlaySystemSound.

  6. When the sound is finished playing, the SoundFinished function is called, which destroys the sound object.