Lessons learned doing sound on iOS – the real story

A few days ago I wrote an article about using sound effects in iOS games. Just today I was doing some more testing and realized I had made a major mistake, and some things I said in that post were wrong. In this post I’ll let you know what I had did wrong.

I alluded to a single line change that would allow playback of MP3 files. Here is the specific line:

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:sampleName ofType:@”caf”];

I had simply changed the “caf” to “mp3” and since I was getting sounds I assumed things were working. The weird staticky sounds I got I explained by saying that several of the same sound were colliding and causing such an effect. Though sound collision can be a problem and sometimes it might make sense to have several variations of a sound effect, what appears to have been actually happening is that OpenAL didn’t know how to process MP3 and so it was just generating random noise.

After a tried a few different .MP3 files and they all sounded pretty much the same, I finally realized what was going on.

The solution was to return the code to use “caf” files, and use a line like the below to convert MP3 files to CAF files.

> afconvert -f caff -d LEI16@44100 chop.mp3 chop.caf

After doing this, my sounds finally started playing properly. I did find some strange effects that occur when sounds overlap quickly, but they were more subtle.

One additional step that is good to know is you will need to manually tell the .caf files you added to your project that they need to be included with the bundle that gets copied to the device. You can do this by dragging the file under XCode’s Build Phases => Copy Bundle Resources. I didn’t notice this problem for MP3 files, as it seems smart enough to add the to this list automatically.

The strange thing is I would expect OpenAL to throw an error somewhere instead of just spitting out noise. So either this set of APIs is pretty badly designed, or there is some code in AudioSamplePlayer that isn’t handling things properly. Either way, I got things working so not going to pry any deeper at this point.