iPhone App Development Tips – Playing multiple sounds using AVAudioPlayer
Tuesday, June 16th, 2009During 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:- (more…)

