我希望在更改 View 时停止播放音频文件。
我正在使用tabController,并且我希望当用户移至其他 View 时停止播放的音频。我不确定该在哪里以及如何进行。在viewDidUnload中?
这是我用来播放音频文件的方法:
-(void)startPlaying {
[NSTimercheduledTimerWithTimeInterval:15目标:自我选择器:@selector(startPlaying)userInfo:无重复:NO];
NSString * audioSoundPath = [[NSBundle mainBundle] pathForResource:@“audio_file” ofType:@“caf”];
CFURLRef audioURL =(CFURLRef)[NSURL fileURLWithPath:audioSoundPath];
AudioServicesCreateSystemSoundID(audioURL,&audioID);
AudioServicesPlaySystemSound(audioID);
}
谢谢你的帮助
最佳答案
在您的 View Controller 中这样的东西(未经测试):
- (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);
}
失踪: