AVCaptureSession and bluetooth microphone
I am working on a video recording app and should be able to use a bluetooth microphone as audio input (if connected).
I have the following code to set up AVCaptureSession audio input:
self.captureSession.usesApplicationAudioSession = YES;
self.captureSession.automaticallyConfiguresApplicationAudioSession = NO;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
self.microphone = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
audioInput = [AVCaptureDeviceInput deviceInputWithDevice:self.microphone error:&error];
if ([self.captureSession canAddInput:audioInput])
{
[self.captureSession addInput:audioInput];
}
The problem is that the bluetooth microphone never appears as an available capture device (although it is paired correctly). Printing out [AVCaptureDevice] results in:
So, no matter what I do, the sound always comes from the iPad's built-in microphone.
source to share
I also ran into this problem in context SFSpeechRecognizer
. I wanted to record audio from a bluetooth microphone and convert it to text. First, I included the input in AVAudioSession
:
// Activate bluetooth devices for recording
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord, with: [.allowBluetooth])
try? AVAudioSession.sharedInstance().setActive(true)
// Configure a bluetooth device for recording if available
let bluetoothRoutes = [AVAudioSessionPortBluetoothHFP]
let availableInputs = AVAudioSession.sharedInstance().availableInputs
if let bluetoothInput = (availableInputs?.filter{ bluetoothRoutes.contains($0.portType) })?.first {
try? AVAudioSession.sharedInstance().setPreferredInput(bluetoothInput)
}
But even after the AVCaptureSession property was set automaticallyConfiguresApplicationAudioSession
to false AVCaptureDevice.devices()
only showed me the built-in microphone and didn't record audio from bluetooth.
I ended up replacing it AVCaptureDevice
with AVAudioRecorder
, which respects re-routing. Now I can write audio to a temporary file that I am transferring to SFSpeechRecognizer
.
source to share