如何监听 iOS 系统 AudioSession 的改变

音频没有声音,很多场景下是因为用户直接或者间接(其他 SDK)修改了音频通话的相关设置引起的,用户可以通过下面的方法监听 AudioSession 的状态改变,可以定位问题发生时,AudioSession 是否有变动:

// AudioSession 状态获取的通知
[[NSNotificationCenter defaultCenter]
                    addObserver:self
                            selector:@selector(audioSessionChange:)
                                name:AVAudioSessionRouteChangeNotification
                               object:[AVAudioSession sharedInstance]];
                               
//相关事件                              
- (void)audioSessionChange:(NSNotification *)notification {
   NSDictionary *interuptionDict = notification.userInfo;
   NSInteger routeChangeReason = [[interuptionDict
                                     valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
   NSString *reason;
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonUnknown:
            reason = @"ReasonUnknown";
            break;
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            reason = @"NewDeviceAvailable";
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            reason = @"OldDeviceUnavailable";
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            reason = @"CategoryChange";
            break;
        case AVAudioSessionRouteChangeReasonOverride:
            reason = @"Override";
            break;
        case AVAudioSessionRouteChangeReasonWakeFromSleep:
            reason = @"WakeFromSleep";
            break;
        case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
            reason = @"NoSuitableRouteForCategory";
            break;
        case AVAudioSessionRouteChangeReasonRouteConfigurationChange:
            reason = @"RouteConfigurationChange";
            break;
    }
}