Game Development Reference
In-Depth Information
Listing 11-10. playAudio: (GameController.m)
-(void)playAudio:(NSString*)audioName{
[self playAudio:audioName volume:1.0 pan:0.0];
}
-(void)playAudio:(NSString*)audioName volume:(float)volume pan:(float)pan{
if (alwaysPlayAudioEffects || !otherAudioIsPlaying){
AVAudioPlayer* player = [audioNameToPlayer valueForKey:audioName];
NSArray* params = [NSArray arrayWithObjects:player, [NSNumber numberWithFloat:volume],
[NSNumber numberWithFloat:pan], nil];
[self performSelectorInBackground:@selector(playAudioInBackground:) withObject:params];
}
}
In Listing 11-10, we see the task playAudio :, which actually calls playAudio:volume:pan: with
some default values. Actors or other game elements can call either version, depending on their
needs. In playAudio:volume:pan:, we can see that we first check if we should actually play a
sound at all. We do this by testing alwaysPlayAudioEffects and otherAudioIsPlaying . The BOOL
alwaysPlayAudioEffects is a property of GameController and indicates if sound effects should ignore
the fact that the user is playing his own audio. In this example, the value of alwaysPlayAudioEffects
is controlled by the switch on the game screen. Flip the switch to experiment with the two different
behaviors. The BOOL otherAudioIsPlaying is set in initializeAudio from Listing 11-2.
If it is determined that we should play a sound, playAudio:volume :pan : continues by finding the
AVAudioPlayer in the NSMutableDictionary audioNameToPlayer associated with audioName . Once
we have the player , we package player up with the volume and pan parameters in an NSArray
called params . We then call performSelectorInBackground:withObject: , passing in the selector
playAudioInBackground: and params .
The task playAudioInBackground: has nothing to do with background music; the word background
indicates that this task should be performed in a background thread, hence the call to performSelect
orInBackground:withObject:. Listing 11-11 shows the implementation of playAudioInBackground: .
Listing 11-11. playAudioInBackground: (GameController.m)
-(void)playAudioInBackground:(NSArray*)params{
AVAudioPlayer* player = [params objectAtIndex:0];
NSNumber* volume = [params objectAtIndex:1];
NSNumber* pan = [params objectAtIndex:2];
[player setCurrentTime:0];
[player setVolume: [volume floatValue]];
[player setPan: [pan floatValue]];
[player play];
}
Search WWH ::




Custom Search