iphone - viewDidUnload-更改 View 时停止方法

标签 iphone objective-c audio

我希望在更改 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);
}

失踪:
  • 检查
  • 错误
  • audioTimer的属性或ivar。
  • 也可以保留相同的计时器,重复YES。
  • 释放dealloc中的资源。
  • 测试
  • 关于iphone - viewDidUnload-更改 View 时停止方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896736/

    相关文章:

    iphone - 单击电子邮件中的音频链接后,如何打开我的应用程序音频播放器来播放音频?

    ios - 检测 iOS 键盘上的 Shift + Enter

    ios - 从 UI BarButtonSystemItem 图标获取图像

    python - PyAudio-同步播放和录制

    math - 在哪里可以找到真正的FFT和iFFT实现?

    iphone - 我们可以在 Tiff 文件中添加自定义键或如何在 Tiff 文件的图像属性中添加温度数据

    iphone - 我想知道IPA文件的执行流程

    macos - 何时在 Apple macOS 上使用 Metal 而不是 Accelerate API

    iphone - 如何创建发光字体?

    objective-c - 收缩和旋转三角形