Audio Tutorial for iOS: Playing Audio Programatically

Ray Wenderlich

This post is also available in: Chinese (Simplified)

Screenshot from BasicSounds sample project

Screenshot from BasicSounds sample project

This article is the third in a three-part Audio Tutorial series covering audio topics of interest to the iPhone developer.

So far in this Audio Tutorial series we’ve talked about the difference between file and data formats and how to convert and record audio on your Mac. Now we’ll get to the fun part – actually playing audio on your phone!

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

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:

  • It only supports audio data formats linear PCM or IMA4.
  • It only supports audio file formats CAF, AIF, or WAV.
  • The sounds must be 30 seconds or less in length.
  • And more – see the iPhone Application Programming Guide, page 149.

AVAudioPlayer

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:

  1. If you’re playing background music, you should check to see if other audio (like the iPod) is playing first, so you don’t have two layers of music going on at once!
  2. If a phone call arrives and the user chooses “Decline”, by default your AVAudioPlayer will stop. You can start it back up again by registering for the AVAudioPlayerDelegate and starting the music back up again in the audioPlayerEndInterruption method.

Sample Code

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!

OpenAL

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.

And That’s a Wrap!

That’s about all I’m going to cover about audio topics in iPhone programming for now – but keep in mind I’ve barely scratched the surface. If you’re interested in more, I’d recommend reading Apple’s docs, especially the Core Audio Overview and Audio Session Programming Guide, and possibly digging into OpenAL a bit more.

I hope this Audio Tutorial series has been useful to other developers who may be new to audio concepts. Feel free to share any additional info you’re aware regarding audio programming that may be useful to others!

Ray Wenderlich

Ray is an indie software developer currently focusing on iPhone and iPad development, and the administrator of this site. He’s the founder of a small iPhone development studio called Razeware, and is passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

User Comments

24 Comments

[ 1 , 2 ]
  • Hi Ray,
    I have a question
    Can we access iphone's default sounds programatically?
    Please provide sample code.........
    srinivas
  • Hey, if I change some of the stuff, do you mind if I submit it to the app store as a free app?
    theappdude
  • @Ray : I want to play a part of complete audio file. For example 30 milliseconds out of 1 second . how can i achieve that?
    jackal13
  • I know this is quite old but I would like to know if you can use SystemSounds to play (very short - about 15 seconds) sounds that are in a NSArray?

    I am using a UIPickerView and in the didSelectRow

    SystemSoundID soundID;
    NSString *chirp = [chirpSounds objectAtIndex:row];
    NSString *soundFile = [[NSBundle mainBundle] pathForResource:chirp ofType:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile], &soundID);
    AudioServicesPlaySystemSound(soundID);


    But it crashes at the AudioServicesCreateSystemSoundID line, is there a better way to do this or should I be using AVAudioPlayer?

    Thanks
    Mercdes1a1 :?
    Mercdes1a1
  • hi
    I need some sound effects to use in an app... I can find a lot of site offering free sound effects but mostly they are of poor quality.
    Someone could please suggest to me from where buy good sound effects?

    thanks in advance!
    ste72
  • Hello Ray,
    Thanks for your great website! I was just recently made aware of your website by a friend of mine.
    I'm new to iOS programming so, I'm in a major learning mode.

    I'm trying to write a Morse code learning app. I want to create the "dit" and "dah" sounds, which are the basis of all the
    Morse code characters, as simple as possible. I want to know how to create these sounds possibly through system sound services.

    Since the "dah" is 3X longer than a "dit" than all I would have to do is manipulate the length of the "dit" sound or should say duration. Also, I need to create a time interval spacing between the "dit" and "dah", between characters, and between words. How would I generate this timed spacing?
    Thanks for your help, in advance.
    Gary W.
    eLearner
  • bobmoff
  • Hello Ray,

    Is there a way to have an audio file be swapped out programmatically with a ringtone when the user selects a certain action and when they select another action their original ringtone is reset?

    Thanks,

    Dean
    carydean7
  • Hey Guys,

    I had some problems using the method for the System Sound Services because it doesn't seem to be ARC friendly. Here is what I ended up doing:

    // You need to include the file and the AudioToolbox framework
    #import

    // Set up an instance variable like so:
    SystemSoundID sound1;

    NSURL *SoundURL = [[NSBundle mainBundle] URLForResource:@"Sample"
    withExtension:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &sound1);

    //Here is the code to start playing the sound:
    AudioServicesPlaySystemSound(sound1);

    Thanks for all your help Ray:)
    Cdava
[ 1 , 2 ]

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in May: Procedural Level Generation in Games with Kim Pedersen.

Sign Up - May

Coming up in June: WWDC Keynote - Podcasters React! with the podcasting team.

Sign Up - June

Vote For Our Next Book!

Help us choose the topic for our next book we write! (Choose up to three topics.)

    Loading ... Loading ...

Our Books

Our Team

Tutorial Team

  • Jean-Pierre Distler
  • Felipe Laso Marsetti

... 55 total!

Editorial Team

... 21 total!

Code Team

  • Orta Therox

... 1 total!

Translation Team

  • Sonic Zhao
  • Team Tyran

... 38 total!

Subject Matter Experts

  • Richard Casey

... 4 total!