是否可以从iPhone的内置麦克风接收音频输入,并同时通过蓝牙耳机播放该音频?
我的目标是始终使用内置麦克风作为输入设备,即使输出设备是耳机,因为在我的用例中内置麦克风更方便。
当输出设备是有线耳机时,我知道如何实现我的目标,就像iPhone附带的那种。我只需插入有线耳机,并调用以下方法:
- (void)selectBuiltInMicrophone
{
AVAudioSession *session = [AVAudioSession sharedInstance];
for (AVAudioSessionPortDescription *port in session.availableInputs)
if ([port.portType isEqualToString:AVAudioSessionPortBuiltInMic]) {
NSError *error;
[session setPreferredInput:port error:&error];
break;
}
}
通过调用上述方法,输入设备将从有线耳机的麦克风切换到iPhone的内置麦克风,而输出设备不受影响,因此iPhone将从内置麦克风录制并通过有线耳机播放。这就是我所期望的。
问题是,当耳机是蓝牙耳机时,此方法不起作用。如果我将蓝牙耳机连接到iPhone,然后调用上述方法,内置麦克风将成为输入设备,这很好,但输出设备也将更改为iPhone的接收器,这很糟糕。
蓝牙耳机的输入和输出似乎被锁定在一起:你要么同时使用它们,要么一个都不使用。我的目标真的不可能实现吗?还是有办法克服明显的局限性?
无法同时接收来自 iPhone 内置麦克风的音频输入,也无法通过蓝牙耳机播放该音频
您可以在通过蓝牙音频设备播放音频时选择特定的麦克风。
// set audio session category to .playAndRecord. use do-catch if you need error-handling
try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothA2DP, .allowBluetooth])
// check if currentRoute is set to a bluetooth audio device
let btOutputTypes: [AVAudioSession.Port] = [.bluetoothHFP, .bluetoothA2DP, .bluetoothLE]
let btOutputs = AVAudioSession.sharedInstance().currentRoute.outputs.filter { btOutputTypes.contains($0.portType) }
// if so, set preferred audio input to built-in mic
if !btOutputs.isEmpty {
let builtInMicInput = AVAudioSession.sharedInstance().availableInputs?.filter { $0.portType == .builtInMic }.first
try? AVAudioSession.sharedInstance().setPreferredInput(builtInMicInput)
} else {
// set default input
try? AVAudioSession.sharedInstance().setPreferredInput(nil)
}
try? AVAudioSession.sharedInstance().setActive(true)
或者你可以按照这里的详细说明https://developer.apple.com/library/archive/qa/qa1799/_index.html
编辑:事实证明,在使用蓝牙耳机作为输出的同时,使用内置麦克风作为输入有更简单的方法。只需像这样设置AVAudio会话的分类选项
// allow only A2DP. you may set other mode or options, excluding .allowBluetooth
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.allowBluetoothA2DP])
通过删除< code >。allowBluetooth来自AVAudioSession的< code>categoryOptions,它不允许HFP,这是一种使用蓝牙设备作为输入的协议。因此,它会自动将其输入路径改为内置麦克风。
如果您有多个输入(例如,如果您的设备连接到usbAudio或lineIn输入设备),您仍然需要使用< code>setPreferredInput来将您的输入路由更改为内置麦克风。