Audio Playback

Any decent game requires sound. Sound creates an atmosphere and pulls the player right into the game's world. Thankfully, Sparrow makes it easy to play sound.

The audio engine needs to be initialized at the game's start, and stopped before the game ends. If you started your project with the latest scaffold project, this will already be done for you.

// at the beginning:
[SPAudioEngine start];
// and at the end:
[SPAudioEngine stop];

Now to the playback. If you’re in a hurry, this one-liner will play audio in any format known to the iPhone:

[[SPSound soundWithContentsOfFile:@"sound.aif"] play];

This loads the sound from a file and starts playback. Don’t worry, the auto release pool won’t touch this sound until it’s done playing.

Normally, though, you'll want to have more control about playback. You will use the following two classes to add sound to your game:

  • SPSound
  • SPSoundChannel

You can imagine this class-couple analog to the “SPTexture” and “SPImage” classes. Just as “SPTexture” contains image data, “SPSound” contains sound data. To display an image, you use “SPImage” — to play a sound, you use “SPSoundChannel”.

So, if you need a sound multiple times, the “SPSound” will be in memory just once, while several “SPSoundChannels” will reference it. Here is a real-life example:

SPSound *sound = [SPSound soundWithContentsOfFile:@"sound.caf"];
SPSoundChannel *channel = [sound createChannel];
channel.volume = 0.6f;
[channel retain]; // always retain the channel, otherwise it will be destroyed
                  // by the autorelease pool! If you don't need to keep it,
                  // call [sound play] instead, then it will handle that itself.
[channel play];
[channel pause];
[channel stop];
[channel addEventListener:@selector(onSoundCompleted:) atObject:self

That should speak for itself. Behind the scenes, the SPSound class will choose the appropriate technology for playback: uncompressed files will use OpenAL, compressed sound will be handled by Apple’s AVAudioPlayer. You don’t have to care. Besides, your sounds will automatically be paused when the application is disrupted (e.g. by a phone call), and will continue playback where they stopped.

You can also set a master volume that influences all sounds at once:

[SPAudioEngine setMasterVolume:0.5f];

The only thing left for you to decide is which file formats to use for your sounds, and how to convert them into this format. There is a blog entry that will teach you all you need to know.

Next section: Macros

  manual_v1/audio_playback.txt · Last modified: 2013/03/05 10:19 (external edit)
Powered by DokuWiki