There are many ways to play audio on the Mac – System Sound Services, AVAudioPlayer, Audio Queue Services, and OpenAL. Without outside support libraries, the two easiest ways by far are System Sound Services and AVAudioPlayer – so let’s talk about when you would (and wouldn’t) want to use those, and how you can use them.
System Sound Services provides an extremely easy way to play audio files. All you have to do is the following:
NSString *pewPewPath = [[NSBundle mainBundle] pathForResource:@"pew-pew-lei" ofType:@"caf"]; NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath]; AudioServicesCreateSystemSoundID((CFURLRef)pewPewURL, &_pewPewSound); AudioServicesPlaySystemSound(_pewPewSound); |
Doesn’t get much easier than that. However there are some strong drawbacks to this method:
So what if you have an audio file encoded with AAC or MP3 that you want to play as background music? Another easy way to play music is via the AVAudioPlayer class. For the most part, it again is quite simple:
NSError *error; _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error]; [_backgroundMusicPlayer prepareToPlay]; [_backgroundMusicPlayer play]; |
However, the drawback of AVAudioPlayer is it is extremely slow. If you tap a button and try to trigger a sound with AVAudioPlayer, there will be a noticeable small delay. But if that doesn’t matter to you (like for starting up background music), AVAudioPlayer is a fine choice.
And there are a couple other things to keep in mind:
I put together some sample code showing how to use System Sound Services and AVAudioPlayer that you might want to check out. Not only does it demonstrate those APIs, it has some mighty funky beats and a cool spaceship to boot. Pew-pew!
If you’re writing a game or another app where you want fine grained control of audio with low latency, you probably don’t want to use the above methods. Instead, you might want to use OpenAL, a cross-platform audio library supported by the iPhone.
OpenAL can be a beast with a steep learning curve. Luckily, Alex Restrepo has extended a great example by gehacktes.net and made a nice Sound Engine library using OpenAL that you can either use in your projects or use as a reference.
Another option is the Cocos2D game library includes an extremely easy to use sound engine that makes playing audio a snap. You can learn how to use it in my tutorial on How To Make a Simple iPhone Game With Cocos2D.