I am creating a sound board app that plays one sound at a time. I would like a UIButton to be able to stop all other sounds playing and start playing its own sound when clicked. I have a single AVAudioPlayer set up to play all sounds (I change the sound file url when clicked and since I only want one sound at a time playing this is not an issue). I would like to know how to stop all other sounds and play the sound according to the button pressed, but if the button clicked is the button with the sound currently playing, the button only stops the sound. I know this is achievable through going to separate audioplayers and triggering the stop event but I want to avoid copy and pasting code and to stay efficient as possible, plus I only want / need a single audioplayer. Here is my code:
- (IBAction)play {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start setTitle:@"Stop" forState:UIControlStateNormal];
}
else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start setTitle:@"Start" forState:UIControlStateNormal];
}
}
- (IBAction)play2 {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/chicken.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start2 setTitle:@"Stop" forState:UIControlStateNormal];
} else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start2 setTitle:@"Start" forState:UIControlStateNormal];
}
}
Any help is appreciated. Thank you in advance!
Just do this
-(void)stopAudio{
if(audioPlayer && [audioPlayer isPlaying]){
[audioPlayer stop];
audioPlayer=nil;
}
}
And call this function on every click..
- (IBAction)play2 {
[self stopAudio];
//Do your Stuffs
}