Game Development Reference
In-Depth Information
Listing 11-7. prepareAudio: (GameController.m)
-(AVAudioPlayer*)prepareAudio:(NSString*)audioName{
if (audioNameToPlayer == nil){
audioNameToPlayer = [NSMutableDictionary new];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:audioName
ofType:@"m4a"]];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error: nil];
[player prepareToPlay];
[audioNameToPlayer setValue:player forKey: audioName];
return player;
}
In Listing 11-7, we see the task
prepareAudio
:. This task is responsible for creating an
AVAudioPlayer
for each audio file passed in. We do this by first lazily initializing an
NSMutableDictionary
called
audioNameToPlayer
, which maps the
NSString audioName
to an
AVAudioPlayer
once constructed. To
create an
NSAudioPlayer
, we first create an
NSURL
pointing to the desired m4a file in the project. To
construct the NSAudioPlayer, we simply call
initWithContentsOfURL:error:
, ignoring any error.
We call
prepareToPlay
on the newly created
player
in order to make sure that the file is loaded and
ready to make sound as soon as we call
play
on it sometime later.
The other sound-related task called in our
doSetup
task, from Listing 11-5, is
playBackgroundAudio
:,
which is shown in Listing 11-8.
Listing 11-8. playBackgroundAudio: (GameController.m)
-(void)playBackgroundAudio:(NSString*)audioName{
if (backgroundPlayer != nil){
[backgroundPlayer stop];
}
backgroundPlayer = [self prepareAudio:audioName];
[backgroundPlayer setNumberOfLoops:-1];
if (!otherAudioIsPlaying){
[backgroundPlayer play];
}
}
In Listing 11-8, the task
playBackgroundAudio
: takes the name of an audio file. If an existing
AVAudioPlayer backgroundPlayer
exits, we stop it. Next, we call
prepareAudio:
to construct
and initialize an
AVAudioPlayer
. To make the audio play indefinitely, we call
setNumberOfLoops:
and specify −1. While we want the background audio to play continuously, we can instead
use
setNumberOfLoops:
to play an audio file a fixed number of times. The naming of the task
setNumberOfLoops:
is a little weird; it indicates the number of extra times a track is played. So,
for example, if you specified 0, the audio would play once (the default number of times). If you
specified 3, the audio track would play 4 times. Basically,
setNumberOfLoops:
specifies the number
of
additional
times the audio should be played.