The Sound Engine

There are typically two purposes for playing a sound in a game application: background music and sound effects. Both end up at the same place, the speakers (or headphones), but due to their different requirements, they need two different routes to get there.

Sound effect files tend to be very short, most of them between one and 10 seconds long, and they don’t take up much memory, partly because their sound quality can be lower than that of music. For our application, we require that they play as soon as we request them to play with little to no latency (so that they are relevant to what is happening on the screen), and we may need to play many of them at once.

However, music files tend to be longer (on the order of one or more minutes) and much larger. So large, in fact, that they need to be compressed to reduce their size, thus the popularity of the .mp3 file format. Unfortunately, that also means they need to be uncompressed when we want to play the file, which requires additional CPU usage. Since we don’t need to play more than one music file at the same time, this is acceptable.

Just as with graphics, the iPhone provides multiple APIs for sound playback. Your decision of which to use will depend on the problem you are trying to solve. For example, OpenAL is good at playing short sound effect files with as little latency as possible, while Audio Queue can be used for playing music from compressed file formats.

A lot of code goes into setting all this up, but Apple ...

Get iPhone Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.