【问题标题】:viewDidUnload - stopping a method when the view is changedviewDidUnload - 当视图改变时停止一个方法
【发布时间】:2011-04-23 05:49:21
【问题描述】:

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

我正在使用 tabController,我希望当用户移动到不同的视图时,正在播放的音频停止。我不确定我会在哪里以及如何做到这一点。也许在 viewDidUnload 中?

这是我用来播放音频文件的方法:

-(void)startPlaying { [NSTimer scheduleTimerWithTimeInterval:15 target:self 选择器:@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); }

感谢您的帮助

【问题讨论】:

    标签: iphone objective-c audio


    【解决方案1】:

    您的视图控制器中的类似内容(未经测试):

    - (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);
    }
    

    缺失:

    • 错误检查
    • audioTimer 的属性或 ivar。
    • 还可以保持相同的计时器,重复 YES。
    • 释放 dealloc 中的资源。
    • 测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多