简体   繁体   中英

Record audio from AirPod microphone

I'm trying to record and speech recognize the audio coming through the microphone of my bluetooth AirPods.

I tried everything I found but with no luck. I'm able to record from the built in microphone but as soon as I set the audio category to bluetooth it crashes.

This is the current version of my code:

askSpeechPermission()

var request = SFSpeechAudioBufferRecognitionRequest()
var listOfInputs = AVAudioSession.sharedInstance().availableInputs

do {
     try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord, mode: AVAudioSessionModeDefault, options: AVAudioSessionCategoryOptions.allowBluetooth)
} catch {

}

let node = audioEngine.inputNode
let recordingFormat = node.outputFormat(forBus: 0)

node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
    self.request.append(buffer)
}

And this is the resulting crash error.

*** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'

Have u tried to check your sample rate. To modify your Sample rate you can use

let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: true)

and then you can it to your format

node.installTap(onBus: 0, bufferSize: 1024, format: fmt) { buffer, _ in
    self.request.append(buffer)
}

i had the same problem and I solved adding the BluetoothA2DP option:

audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
              withOptions:(AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetoothA2DP)
                    error:nil];

Follow Osman suggestion, I can fix the problem by set the sample rate as the AudioSession sample rate

let sampleRate = AVAudioSession.sharedInstance().sampleRate
let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: 1, interleaved: true)
node.installTap(onBus: 0, bufferSize: 1024, format: fmt) { buffer, _ in
    self.request.append(buffer)
}

Hope this help someone~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM