2

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.

2 Answers2

0

You can add the stop method in the current class and call that methos in the other class on button click.Please find the code snippet on the following link

Trigger AVAudioPlayer to stop all sounds and play selected except when playing(selected) button is clicked

Adding one more link Why does the AVAudioPlayer stop method not work when switching views

Community
  • 1
  • 1
creative_rd
  • 695
  • 6
  • 13
0

Declare the instance of AVAudioPlayer at .h file as Global.

@property (nonatomic, retain) AVAudioPlayer *theAudio;

You can stop this from another controller

[objViewController.theAudio stop];

This works for me ..Hope it helps you too..

Kumar KL
  • 15,315
  • 9
  • 38
  • 60
  • I've already tried this but the sound won't stop. I edited my question. –  Oct 23 '13 at 11:14