This is the “Soundplay” example. There are many ways to implement the sound in iPhone. I am going to show you the simplest way to play the sound.
Step 1: Open the Xcode and create a new Xcode project using View base application template. Give the application name “soundplay”. As shown in the figure below:
Step 2: Expand classes and notice Interface Builder created the SoundplayViewController.h and SoundplayViewController.m class for you. Expand Resources and notice the template generated a separate nib, SoundplayViewController.xib.
Step 3: In this application, we need to add two frameworks.So select Frameworks -> Add -> Existing Framework -> then select AVFoundation.framework and AudioToolbox.framework.
Step 4: We need to add sound files in the Resources folder. Give the name of the sound files “play.wav”.
Step 5: Open the SoundplayViewController.h file and we have to add IBOutlet UIButton *Soundstart to display the button and mention two IBAction to perform the given action. So make the following changes in the file.
@interface SoundPlayViewController : UIViewController
{
//SoundID SID;
IBOutlet UIButton *Soundstart;
}
@property(nonatomic,retain)IBOutlet UIButton *Soundstart;
–(IBAction) soundplay:(id) sender;
–(IBAction) soundstop:(id) sender;
@end
Step 6: Double click the SoundplayViewController.xib file and after that make the following changes.
A) Open the view window, first drag the RoundRect Button from the library and place it to the view window and select the button.
B) Connect File’s Owner icon to two button and select “View”.
Once this is done, save the SoundplayViewController.xib file, close it and go back to the Xcode.
Step 7: Open the TableViewViewController.m file and make the following changes in the file.
#import <AVFoundation/AVFoundation.h>
@implementation SoundPlayViewController
@synthesize Soundstart;
AVAudioPlayer *player;
–(IBAction)soundplay:(id)sender
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/play.wav"];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(@"Failed with reason: %@", [err localizedDescription]);
}
else{
//set our delegate and begin playback
player.delegate = self;
[player play];
}
}
–(IBAction)soundstop:(id)sender
{
if (player != nil && [player isPlaying])
{
[player stop];
}
}
Step 8: Now build and run the code and view the Output in the Simulator.
You can download source code from here SoundPlay