0
votes

I'm looking to stop an audio file from playing when the view is changed.

I'm using a tabController and I would like the audio that's playing to stop when the user moves to a different view. I'm not sure where and how I would do this. in the viewDidUnload perhaps?

here's the method I'm using to play the audio file:

-(void)startPlaying { [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(startPlaying) userInfo:nil repeats:NO];

NSString *audioSoundPath = [[ NSBundle mainBundle] pathForResource:@"audio_file" ofType:@"caf"]; CFURLRef audioURL = (CFURLRef) [NSURL fileURLWithPath:audioSoundPath]; AudioServicesCreateSystemSoundID(audioURL, &audioID); AudioServicesPlaySystemSound(audioID); }

thanks for any help

1

1 Answers

2
votes

Something like this in your view controller (untested):

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Load sample
    NSString *audioSoundPath = [[NSBundle mainBundle] pathForResource:@"audio_file"
                                                                ofType:@"caf"];
    CFURLRef audioURL = (CFURLRef)[NSURL fileURLWithPath:audioSoundPath];
    AudioServicesCreateSystemSoundID(audioURL, &audioID)
}

- (void)viewDidUnload
{
    // Dispose sample when view is unloaded
    AudioServicesDisposeSystemSoundID(audioID);

    [super viewDidUnload];
}

// Lets play when view is visible (could also be changed to viewWillAppear:)
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self startPlaying];
}

// Stop audio when view is gone (could also be changed to viewDidDisappear:)
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if([self.audioTimer isValid]) {
        [self.audioTimer invalidate];
    }
    self.timer = nil;
}

// Start playing sound and reschedule in 15 seconds.
-(void)startPlaying
{
    self.audioTimer = [NSTimer scheduledTimerWithTimeInterval:15 target:self   
                                                     selector:@selector(startPlaying)
                                                     userInfo:nil
                                                      repeats:NO];
    AudioServicesPlaySystemSound(audioID);
}

Missing:

  • Error checking
  • Property or ivar for audioTimer.
  • Could also keep the same timer, with repeats YES.
  • Freeing resources in dealloc.
  • Testing