观察 AVAudioSession 不触发通知

Observing AVAudioSession not firing notifications

在我目前正在构建的应用程序中,我需要根据 [AVAudioSession sharedInstance] 的当前类别处理一些事情。这个类别会在运行时发生变化,我试图通过在 NotificationCenter 中观察 AVAudioSessionRouteChangeNotification 来跟踪变化。

但是,无论我尝试什么,通知都没有被触发(或者至少我的选择器方法没有收到任何东西)。

部分测试示例代码;

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionRouteDidChange:) name:AVAudioSessionRouteChangeNotification object:nil];
   return YES;
}
- (void)sessionRouteDidChange:(NSNotification *)notification
{
    NSLog(@"SESSION ROUTE CHANGED");
}

ViewController.m

- (void)changeAudioCategory:(AVAudioSessionCategory)category{
       [[AVAudioSession sharedInstance] setActive:NO error:nil];
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *setCategoryError = nil;
        BOOL success = [audioSession setCategory:category error:&setCategoryError];
        if (!success) {
            NSLog(@"ERROR");
        }
        [audioSession setActive:YES error:nil];

        /* Logging the current category */
        NSLog(@"AVAUDIOSESSION CATEGORY %@", audioSession.category);
}

我希望我在 AppDelegate 中设置的观察者在此方法中更改类别后向 sessionRouteDidChange 发送通知,但没有任何反应。

我试过了;

关于我遗漏的任何想法?

更改类别不是路线更改,因此不会post通知。你想要的是 KVO observe category 属性.

当您更改音频路由时,例如,当您插入耳机时,路由会发生变化。