Presentation is loading. Please wait.

Presentation is loading. Please wait.

Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to add sounds to our app.

Similar presentations


Presentation on theme: "Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to add sounds to our app."— Presentation transcript:

1 Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to add sounds to our app

2 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

3 AVFoundation framework #import 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

4 .h file Add an AVAudioPlayer instance variable AVAudioPlayer *cannonFireSound; In the.m file, we need to find this sound file, allocate memory for and initialize the object above

5 .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

6 .m file Get File path NSString *soundPath = [[NSBundle mainBundle] pathForResource:@”cannon_fire” ofType:@”wav”]; Build NSURL object NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundPath];

7 .m file Allocate memory and initialize hitPlayer cannonFireSound = [[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];

8 .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];

9 AVAudioPlayer There may be a lag the first time you play a sound  preload the sound using the prepareToPlay method [cannonFireSound prepareToPlay];

10 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

11 Making a sound when cannon is fired Cannon is fired on a double tap by the user In processTouch method if( touch.tapCount == 2 ) [cannonFireSound play];


Download ppt "Making a sound When we fire a bullet, we will play a sound The AVFoundation framework enables us to add sounds to our app."

Similar presentations


Ads by Google