Thursday, May 7, 2009

Playing multiple sound effects on the iPhone

Looking for a quick and admittedly very dirty solution for playing sound effects in an iPhone app? Then try this free source code. It uses OpenAL for the sound playing and supports mixing of 32 simultaneous sound effects, along with playing one background music track.

PLEASE NOTE: This code was based on Apple's 1.7 SoundEngine code available from the Crash Landing demo supplied with the iPhone SDK 2.0.

Apple has acknowledged significant problems with the original code and has in fact removed the code from all future SDKs. Per the original source code agreement, Apple grants the right to anyone to modify and reuse the software in any manner (see Apple's original licensing agreement in the source files). As such, I have changed the structure of the code to better suit my needs and I am making it available to anyone who might find it useful.

Why use SoundEngine as a base? Isn't oalTouch a better example?

Yes, oalTouch is a much cleaner example, but it makes some API calls that require SDK 2.1. SoundEngine was made for SDK 2.0. I have an app that has already been released on iTunes using the 2.0 OS and needed to add some sound support to it. So, I had to use oalTouch's ugly third cousin as a starting point.

My main motivation for modifying the SoundEngine code was to alter it for providing a means to easily play the same sound effect multiple times, with the playing times overlapping. The SoundEngine as originally written would not do this. Each instance of the sound was bound directly to an OpenAL source, which meant you could only play each sound effect once at a time. If you wanted to play the same sound mutiple times, you have to load the sound mutiple times, which was very wasteful with memory.

This new version of the code allows sharing of the same source sound data buffer.

You can read more details and find a link for the source code here

All content copyright © 2009  Brian Stormont, unless otherwise noted.   All rights reserved.