I have a basic beep sound that I loaded with AVAudioPlayer in my app.
It can play the beep fine if my finger isn’t panning my MKMapView.
My beep is set to play every 2 seconds.
When I start panning the map view, and don’t take my finger off the screen, the beep stops playing.
I recall NSUrlConnection also doesn’t fire while scrolling a table view, I thought this might be the same problem but I couldn’t figure out how I can add my audio player to the proper run loop.
I setup my player like this:
-(void)setupBeep
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/beep.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if(error)
{
NSLog(@"Error opening sound file: %@", [error localizedDescription]);
}
}
and I am playing my sound like this:
// plays a beeping sound
-(void)beep
{
[audioPlayer play];
}
Anyone came across this problem before?
How have you scheduled your
-beepmethod to be called?I suspect you’ve added an
NSTimerto the main run loop in the default input mode. The reason you’re not hearing anything is that whileMKMapViewis tracking your finger, the run loop is in not inNSDefaultRunLoopMode—it’s inUITrackingRunLoopMode.Try scheduling in
NSRunLoopCommonModes, which includes both default and tracking modes:Also, be aware that
NSTimerretains its target. A repeating timer will reschedule itself automatically, so you’ll need to call its-invalidatemethod to remove it from the loop and allow the target to be released.EDIT: Check out Apple’s Threading Programming Guide: Run Loops for a much more detailed explanation.