视图更改时停止方法

我期待在视图更改时停止播放音频文件。

我正在使用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);
}

失踪:

  • 错误检查
  • 属性或ivar为audioTimer。
  • 也可以保持相同的计时器,重复YES。
  • 释放dealloc中的资源。
  • 测试
  • 链接地址: http://www.djcxy.com/p/67931.html

    上一篇: stopping a method when the view is changed

    下一篇: Playing short sound on timer end?