iOS14 Objective-C设置麦克风极性为stereo后仍为Omnidirectional问题
问题根因与修复方案
核心错误点
- 配置顺序错误:你先为未激活的数据源设置极性,再将该数据源设为首选,系统不会将未激活数据源的参数同步到生效配置中,导致极性设置被忽略。
- 属性校验逻辑错误:你读取的
preferredDataSource是你提交的期望配置,只有selectedDataSource才是系统实际生效的配置,日志中preferredInput的selectedDataSource为Bottom,和你选的Front数据源不一致,说明数据源本身就没有成功生效。
修复步骤
- 调整配置顺序,遵循「选输入源→选数据源并校验生效→配置极性→配置朝向」的优先级
- 所有配置校验全部读取
selected开头的系统生效属性,不要读取preferred开头的请求属性 - 确认运行设备为iPhone 11及以上机型(仅该系列之后的设备支持内置麦克风立体声采集),且无外接音频输入设备
- 所有配置完成后主动激活AVAudioSession,强制同步配置到系统
修正后的核心代码示例
- (BOOL)_configureMicrophoneInputDirectionality:(NSError **)outError { AVAudioSessionPortDescription *preferredInput = _audioSession.preferredInput; NSArray<AVAudioSessionDataSourceDescription *> *dataSources = preferredInput.dataSources; AVAudioSessionDataSourceDescription *targetDataSource = nil; AVAudioSessionOrientation audioSessionOrientation = _AudioSessionOrientation(); for (AVAudioSessionDataSourceDescription *dataSource in dataSources) { if ([dataSource.dataSourceName isEqualToString:audioSessionOrientation]) { targetDataSource = dataSource; break; } } if (!targetDataSource) { *outError = [NSError errorWithDomain:@"class_name" code:0 userInfo:@{@"message" : @"未匹配到对应朝向的麦克风数据源"}]; return NO; } NSArray<AVAudioSessionPolarPattern> *supportedPolarPatterns = targetDataSource.supportedPolarPatterns; BOOL isStereoSupported = NO; if (@available(iOS 14, *)) { isStereoSupported = [supportedPolarPatterns containsObject:AVAudioSessionPolarPatternStereo]; } if (!isStereoSupported) { *outError = [NSError errorWithDomain:@"class_name" code:1 userInfo:@{@"message" : @"当前数据源不支持立体声极性"}]; return NO; } // 第一步:先设置目标数据源为首选 BOOL dataSourceSetRes = [preferredInput setPreferredDataSource:targetDataSource error:outError]; if (!dataSourceSetRes) return NO; // 校验数据源是否真的生效 AVAudioSessionDataSourceDescription *selectedDataSource = preferredInput.selectedDataSource; if (![selectedDataSource isEqual:targetDataSource]) { *outError = [NSError errorWithDomain:@"class_name" code:2 userInfo:@{@"message" : @"目标数据源未被系统生效"}]; return NO; } // 第二步:给已生效的数据源设置立体声极性 BOOL polarPatternSetRes = NO; if (@available(iOS 14, *)) { polarPatternSetRes = [selectedDataSource setPreferredPolarPattern:AVAudioSessionPolarPatternStereo error:outError]; } if (!polarPatternSetRes) return NO; // 第三步:设置输入朝向 BOOL orientationSetRes = NO; if (@available(iOS 14, *)) { orientationSetRes = [_audioSession setPreferredInputOrientation:_AudioStereoOrientationFromAudioSessionOrientation(audioSessionOrientation) error:outError]; } if (!orientationSetRes) return NO; // 强制同步配置 [_audioSession activateWithOptions:0 error:outError]; if (*outError) return NO; // 校验实际生效的极性 NSLog(@"实际生效极性=%@", selectedDataSource.selectedPolarPattern); return YES; }
内容的提问来源于stack exchange,提问作者h.and.h
相关产品推荐
相关产品推荐

