iPhone App Development Tips – Playing multiple sounds using AVAudioPlayer
During my journey through App development for the iPhone I will be posting some code that initially gave me a headache and I either managed to solve myself or my good friend Hardy from Catamount Software helped me with.
The first block of code is something that i was struggling with for my latest app called iAnnoyance which is an annoying sounds app. The result i wanted was to have multiple sounds ready to play (.mp3) but each one if triggered must be stopped upon triggering another. In laymens terms “I wanted to stop one sound when another was playing”.
The avenue I decided to go up was the AVAudioPlayer route which I chose for the functionality such as looping and play, stop, pause functions.
So rather than create a seperate player for each sound it was decided that the app could use a single player that would watch the button presses and work out which sound needed to be loaded on the fly. This was achieved using the following code in my MainViewController.m
-(void)playSound:(NSString*)soundName
{
if (self.currentSound.isPlaying)
{
[self.currentSound stop];
}
if (![self.lastSoundPlayed isEqual:soundName])
{
NSString *soundPath = [[NSBundle mainBundle]
pathForResource:soundName ofType:@"mp3"];
AVAudioPlayer *player = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:soundPath] error:NULL];
[player setDelegate:self];
[player prepareToPlay];
[player play];
self.currentSound = player;
[player release];
self.lastSoundPlayed = soundName;
}
}
Each button would then look like so:-
-(IBAction)cryBaby:(id)sender{
[self playSound:@"Cry"];
}
-(IBAction)snoringMan:(id)sender{
[self playSound:@"Snore"];
}
Then make sure you release the sounds and free up memory at the end of the file using the following:-
[currentSound release]; [lastSoundPlayed release];
currentSound & lastSoundPlayed were also added to the top of the file using the following:-
@synthesize currentSound; @synthesize lastSoundPlayed;
My MainViewController.h would then have the following added:-
#import <AVFoundation/AVAudioPlayer.h>
And the following:-
@interface MainViewController : UIViewController <AVAudioPlayerDelegate> {
                       AVAudioPlayer *currentSound;
                       NSString *lastSoundPlayed;
                       }
@property (retain) AVAudioPlayer *currentSound;
@property (retain) NSString *lastSoundPlayed;
Using this code you can set up your buttons to listen for your button presses and stop or start a sound respectively. Hopefully this will help you in your App development and as usual, if you have any questions feel free to post them below.
Tags: Apple Mac, iPhone, iPhone Development


January 26th, 2010 at 12:49 am
Hi there,
Great post but I am having trouble! my application terminates soon as I press a button, are you able to send me the code so I can check I have definately got everything in the right order?
Cheers again
Stu