stopping a method when the view is changed
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
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:
上一篇: 为什么我的音频不能按时播放?
下一篇: 视图更改时停止方法