视图更改时停止方法
我期待在视图更改时停止播放音频文件。
我正在使用tabController,我希望播放的音频在用户移动到不同的视图时停止。 我不确定我会在哪里以及如何做到这一点。 在viewDidUnload也许?
这里是我用来播放音频文件的方法:
- (void)startPlaying {[NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(startPlaying)userInfo:nil repeatats:NO];
NSString * audioSoundPath = [[NSBundle mainBundle] pathForResource:@“audio_file”ofType:@“caf”]; CFURLRef audioURL =(CFURLRef)[NSURL fileURLWithPath:audioSoundPath]; AudioServicesCreateSystemSoundID(audioURL,&audioID); AudioServicesPlaySystemSound(AUDIOID); }
谢谢你的帮助
类似于你的视图控制器(未经测试):
- (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);
}
失踪: