从AirPod麦克风录制音频

5

我试图录制并语音识别从我的蓝牙AirPods麦克风传来的音频。

我尝试了我找到的所有方法,但都没有成功。我能够从内置麦克风录制,但一旦我将音频类别设置为蓝牙,它就会崩溃。

这是我代码的当前版本:

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)
}

这是导致崩溃的错误信息。

*** 因错误异常 'com.apple.coreaudio.avfaudio' 而终止应用程序,原因为:'required condition is false: format.sampleRate == hwFormat.sampleRate'


请添加“func”和您缺少的“{”... - Zyntx
3个回答

1

您是否尝试过检查样本率。要修改样本率,您可以使用

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

然后您可以将它转换为您的格式。
node.installTap(onBus: 0, bufferSize: 1024, format: fmt) { buffer, _ in
    self.request.append(buffer)
}

我尝试了你的建议,但在installTap阶段仍然出现相同的错误导致程序崩溃。 - Viper8

1

我曾经遇到过同样的问题,后来我通过添加BluetoothA2DP选项解决了它:

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

谢谢!这就是对我有效的方法。我的使用情况与OP非常相似,所以我只需将类别设置为record,在选项中列出allowBluetooth,因为我对播放音频不感兴趣,只对捕获和处理音频感兴趣。但由于某种原因,仅仅使用这些设置无法从Airpods捕获音频。 - leandrodemarco

0

按照Osman的建议,我可以通过将采样率设置为AudioSession采样率来解决问题。

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)
}

希望这可以帮助到某个人~

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接