Saturday, August 24, 2013

iOS Tip - Playing Sound

A very common task in iOS is playing sound. For example, your application needs to play some background audio when the user clicks on some buttons, etc.

You can make use of the AudioServicesPlaySystemSound() method in the AudioToolbox.framework to play back an audio file.

First, you need to add the AudioToolbox.framework to your project and then import its header file:


Then, assuming your project has an audio file named c9.aiff, the following code snippet will play back the audio file:

    SystemSoundID soundID;   
    NSString *soundPath =
        [[NSBundle mainBundle] pathForResource:@"c9"
    NSURL *soundPathURL = [NSURL fileURLWithPath:soundPath];
        (__bridge CFURLRef)soundPathURL, &soundID);

If you do not have an audio file and want to play the sound that is already available on your iOS device, you can specify the system sound ID directly, like this:
    int systemSoundID = 1304;
    AudioServicesPlaySystemSound (systemSoundID);

The list of system sound ID is available here:

No comments: