我需要用 16,000Hz 采样的麦克风录制音频信号。我正在使用 AVAudioEngine 和 Swift:
let input = audioEngine.inputNode
let mixer = AVAudioMixerNode()
audioEngine.attach(mixer)
let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 16000.0, channels: 1, interleaved: false)
audioEngine.connect(input, to: mixer, format: input.inputFormat(forBus: 0))
mixer.installTap(onBus: 0, bufferSize: 2048, format: format) {
(buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in ... }
不幸的是,应用程序因以下错误而崩溃:
central] 54: ERROR: [0x3b281e40] >avae> AVAudioNode.mm:751: AUSetFormat: error -10868 *** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -10868'
我做错了什么?
我的想法是使用混频器节点将采样率从 44100 Hz 降低到 16000Hz。
有没有比使用混合器更好的解决方案?
编辑:
使用 AVAudioCommonFormat.pcmFormatFloat32 而不是 AVAudioCommonFormat.pcmFormatInt16 效果更好。它不会导致错误消息或应用程序崩溃,而且在我的 iPhone 5 上它甚至可以接收到正确的声音信号。 但是,在 Xcode 模拟器 (iPhone 7/iPhone X) 中,我只收到 0 作为样本。我在模拟器中用麦克风测试了 Siri,它工作正常,所以麦克风没有坏。 可能是什么问题?
最佳答案
我发现唯一可以改变采样率的是
AVAudioSettings.sharedInstance().setPreferredSampleRate(...)
遗憾的是,虽然 8000、12000、16000、22050、44100 似乎都有效,但无法保证您会获得所需的采样率。
以下无效:
- 在关闭 engine.inputNode 中设置我的自定义格式。 (异常(exception))
- 使用我的自定义格式添加混音器并点击它。 (异常(exception))
- 添加一个混音器,将其与 inputNode 的格式连接,将混音器连接到具有我自定义格式的主混音器,然后移除 outputNode 的输入,以免将音频发送到扬声器并获得即时反馈。 (有效,但全为零)
- 在 AVAudioEngine 中根本不使用我的自定义格式,而是使用 AVAudioConverter 从我的水龙头中的硬件速率进行转换。 (未设置缓冲区的长度,无法判断结果是否正确)
这是针对 iOS 12.3.1 的。
关于iOS/swift : Record audio with 16khz on every hardware using AVAudioEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49370169/