Playing short sounds in iOS.

Playing sounds in iOS can be realized in many ways. This solution shows how to play short sounds using SystemSoundID. It’s a perfect fit for playing short sounds in a small game or menu of your application.

Playing short sounds.

Playing Short SoundsFirst thing we’re going to do is adding the required AudioToolbox framework to Xcode project. Picture on the right side shows how to do it.

Now the coding part. First of all we have to import AudioServices.h to our project.

#import <AudioToolbox/AudioServices.h>

Than we can create a container for our sounds. It can be either an array of SystemSoundIDs, NSMutableArray or a single SystemSoundId object.

SystemSoundID sounds[10];

Now we have to initialize our sound. Let’s create it for example in the viewDidLoad method.

// Path for our sound:
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"my-sound" ofType:@"wav"];

CFURLRef soundURL = (__bridge CFURLRef)[NSURL fileURLWithPath:soundPath];

AudioServicesCreateSystemSoundID(soundURL, &sounds[0]);

Now, all we have to do to play it is execute one line of code.

AudioServicesPlaySystemSound(sounds[0]);

5 thoughts on “Playing short sounds in iOS.

Leave a Reply