Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to...
-
Upload
melissa-wells -
Category
Documents
-
view
212 -
download
0
Transcript of Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to...
Making a sound
• When we fire a bullet, we will play a sound
• The AVFoundation framework enables us to add sounds to our app
AVFoundation framework
• We need to import that framework into our project (it is not in the frameworks folder)
• In Project Navigator, select Build Phases tab, Select Link Binary With Libraries, +, choose AVFoundation Framework
• It shows up in the frameworks folder
AVFoundation framework
#import <AVFoundation/AVFoundation.h>
• We will use the AVAudioPlayer class
• It encapsulates a sound: it enables us to play a sound, stop playing the sound, set the volume, ..
• Note: need to import the sound into the resources folder
.h file
• Add an AVAudioPlayer instance variableAVAudioPlayer *cannonFireSound;• In the .m file, we need to find this sound
file, allocate memory for and initialize the object above
.m file
• Inside initWithFrame method• The method initWithContentsOfURL, from
class AVAudioPlayer, takes a NSURL argument representing the url path of the sound file
• From a string representing a regular file path, we can build a NSURL object
.m file
• Get File pathNSString *soundPath = [[NSBundle
mainBundle] pathForResource:@”cannon_fire” ofType:@”wav”];
• Build NSURL objectNSURL *fileURL = [[NSURL alloc]
initFileURLWithPath:soundPath];
.m file
• Allocate memory and initialize hitPlayercannonFireSound = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];• Now we can set the volume, play the sound,
pause, stop, ..• More at developer.apple….cannonFireSound.volume = 0.9; // between 0
and 1[cannonFireSound play];
.m file
• We used the alloc method to allocate memory for and create the fileURL object
• In previous versions of Xcode only (but not with Xcode 5)
we own that object, we are responsible for releasing it
[fileURL release];
AVAudioPlayer
• There may be a lag the first time you play a sound
preload the sound using the prepareToPlay method
[cannonFireSound prepareToPlay];
Making a sound when cannon is fired
• When do we fire the cannon?• The cannon will fire based on user double
tapping• We need to add some code to the processTouch
method and capture a double tap
Making a sound when cannon is fired
• Cannon is fired on a double tap by the user• In processTouch methodif( touch.tapCount == 2 )
[cannonFireSound play];