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 are in a hurry, the following one-liner will play audio in any format known to iOS. This code loads the sound from a file and starts playback right away.

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

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:

// load sound
SPSound *sound = [SPSound soundWithContentsOfFile:@"sound.caf"];
// create sound channel
SPSoundChannel *channel = [sound createChannel];
channel.volume = 0.6f;
// use channel to control playback.
[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.

Note that you should save a reference to the channel as a member variable! If it's just in a local variable, it will quickly be destroyed by the autorelease pool and you won't hear anything.

If you don't need to keep it, call [sound play] instead; that method takes care of this fact automatically.

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.

Continue to Finished Part I

  manual/audio_playback.txt · Last modified: 2013/05/29 17:25 by daniel
Powered by DokuWiki