I use AVAudioPlayer to play sound on my app. I can stop the sound by just calling a method with [audioPlayer stop];
in it. But when I call the method from another ViewController the sound is not stopping. I already searched but I can't get the right answer. What I want is to stop the sound from another ViewController. Can someone help me? I am new to iOS.
I used this to add my sound file:
//Declare the audio file location and settup the player
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:@"alarm" withExtension:@"wav"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error) {
NSLog(@"%@", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:@"Unable to load file"];
[[self alertLabel] setHidden:NO];
} else {
[[self alertLabel] setText:[NSString stringWithFormat:@"%@ has loaded", @"alarm.wav"]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];}
And used [audioPlayer play];
to start the sound and to stop I used [audioPlayer stop];
. It is working fine when I am on the same ViewController but when I change ViewController [myViewController.audioPlayer stop];
is not working. I am using Storyboard with this.