As the title says, I need to route audio data from the phone's microphone out to AirPods or other connected headphones with AVAudioEngine. I've been able to get a version of this working where input is taken from the AirPods mic, but when I set the preferred input source of the AVAudioSession to the built in iPhone mic, I get no output.
Some relevant snippets of my code:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: [.allowBluetooth])
try AVAudioSession.sharedInstance().setMode(.voiceChat)
if let phoneMicIndex = AVAudioSession.sharedInstance().availableInputs?.firstIndex(where: { $0.portType == .builtInMic }) {
try AVAudioSession.sharedInstance().setPreferredInput(AVAudioSession.sharedInstance().availableInputs?[phoneMicIndex])
}
self.audioEngine.connect(self.audioEngine.inputNode, to: drc, format: self.audioEngine.inputNode.outputFormat(forBus: Config.bus))
self.audioEngine.connect(drc, to: self.audioEngine.mainMixerNode, format: self.audioEngine.outputNode.outputFormat(forBus: Config.bus))
// drc is just an audio unit...
self.audioEngine.inputNode.installTap(onBus: Config.bus, bufferSize: AVAudioFrameCount(Config.bufferSize), format: self.audioEngine.inputNode.inputFormat(forBus: Config.bus), block: { (buffer: AVAudioPCMBuffer, time: AVAudioTime) in
// I get audio data here, it just isn't played out via the AirPods...
})