Game Development Reference
In-Depth Information
After this, we need to create a new method to set up the playback sound. Add this
new method to ERGMyScene.m :
- (void) setupMusic
{
NSString *musicPath = [[NSBundle mainBundle]
pathForResource:@"Kick_Shock" ofType:@"mp3"];
self.musicPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:musicPath] error:NULL];
self.musicPlayer.numberOfLoops = -1;
self.musicPlayer.volume = 1.0;
[self.musicPlayer play];
}
In the first line, we created a path to our background music file. Next,
we initialized AVAudioPlayer —a class that plays music from AVFoundation .
Then, we set numberOfLoops , the property that says how many times the
music should be repeated.
Next up is volume; it is set to 1.0 and sends play messages to the player.
After you have done this, call [self setupMusic] at the end of the initWithSize:
method of ERGMyScene.m but before the return statement.
In a few lines, we managed to add background music to our game. But we will
want to stop music playback if the Game Over screen is called. To do this, locate the
- (void) gameOver method in ERGMyScene.m , and add the [self.musicPlayer
stop]; line at the beginning of it. This will stop music playback.
We will also add short playback sounds to our game. We will have them for shield
charging and depleting. We won't use AVFoundation for this, as there is a simple
sound playback action in Sprite Kit. It is used in this way (don't add this code to
the project):
SKAction *soundAction = [SKAction playSoundFileNamed:@"name.mp3"
waitForCompletion:YES];
[self runAction:soundAction];
It works as any other action. You create an action and run it against the node.
Wait for completion means that the action is considered done as soon as it runs
if waitForCompletion is NO , and the action is considered running if you pass
YES to it.
 
Search WWH ::




Custom Search