1

I made a sound loop in my app that I want to stop when the user presses the 'ok' button on a UIAlertView that comes up.

I have 2 problems though:


First

When I have breakpoints on and I set a breakpoint for all exceptions, an exception appears on [audioPlayer play] but no error is shown on the log and the app does not crash after 'F8-ing' through the exception except there is no sound.


Second

The other problem I'm having is that the audio file wont stop after the user taps the 'ok' button, and breakpointing through shows that it does read the [audioPlayer stop] call. I have no idea what is causing these errors and nothing I do seems to help.


Code

AVAudioPlayer *audioPlayer;


-(void)done {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Timer Done" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
    [alert show];

    [self playAlert];
}

-(void)playAlert {
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    audioPlayer.numberOfLoops = -1; //infinite

    [audioPlayer play];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if ([audioPlayer isPlaying]) {
            [audioPlayer stop];
        }
    }
}

Please let me know what I can do to fix this.

IluTov
  • 6,807
  • 6
  • 41
  • 103
cory ginsberg
  • 2,907
  • 6
  • 25
  • 37

1 Answers1

1

One obvious problem is that you passed nil as the UIView delegate so you will never get called back.

i.e.

   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Timer Done" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];

should be:

   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Timer Done" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];

Another problem is that the buttonIndex starts at zero. So on the callback you should check for zero not one.

Shane Powell
  • 13,698
  • 2
  • 49
  • 61