首页 > 解决方案 > 如何在 Swift 中同时进行 SFSpeechRecognition 和录制音频?

问题描述

因此,我一直在尝试使用内置的 SFSpeechRecognition 类在 Swift 中进行语音识别,同时还进行下采样,然后将音频录制到文件中,但我对 AVAudioEngine 的了解还不够,无法弄清楚。

我已经让语音识别自己工作,我已经让录音自己工作,但我不能让他们一起工作。

这是我尝试记录的现有代码 - 其余代码只是标准语音识别类型的东西:

let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)
let mixer = AVAudioMixerNode()
audioEngine.attach(mixer)


audioEngine.connect(inputNode!, to: mixer, format: inputNode!.inputFormat(forBus: 0))

// 1 Connecting Mixer
audioEngine.connect(mixer, to: audioEngine.outputNode, format: audioFormat)

// 2 Recognition
inputNode!.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
        print("Testing if this tap works")
        self.recognitionRequest?.append(buffer)
    }

// 3 Downsampling and recording
mixer.installTap(onBus: 0, bufferSize: 1024, format: audioFormat){ (buffer, when) in
        print(buffer)
        try? self.outputFile!.write(from: buffer)
}

如果我注释掉 3,那么语音识别就会起作用,但否则 2 甚至都不会运行——点击不会输出任何东西。我也不能将识别请求放在 3 中,因为这样语音识别会引发错误。我在文档中看到每辆公共汽车只能有一个水龙头 - 我该如何解决这个问题?我应该使用 AVConnectionPoint 吗?我没有在文档中看到它的详细记录。

标签: swiftavfoundation

解决方案


推荐阅读