我希望在更改视图时停止播放音频文件。
我正在使用tabController,我希望当用户移动到不同的视图时播放的音频停止。我不知道我会在哪里以及如何做到这一点。在viewDidUnload中也许?
这是我用来播放音频文件的方法:
- (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); }
感谢您的帮助
答案 0 :(得分:2)
你的视图控制器中有类似的东西(未经测试):
- (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);
}
缺失: