iOS/swift : Record audio with 16khz on every hardware using AVAudioEngine

标签 ios swift xcode avaudioengine

我需要用 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 似乎都有效,但无法保证您会获得所需的采样率。

以下无效:

  1. 在关闭 engine.inputNode 中设置我的自定义格式。 (异常(exception))
  2. 使用我的自定义格式添加混音器并点击它。 (异常(exception))
  3. 添加一个混音器,将其与 inputNode 的格式连接,将混音器连接到具有我自定义格式的主混音器,然后移除 outputNode 的输入,以免将音频发送到扬声器并获得即时反馈。 (有效,但全为零)
  4. 在 AVAudioEngine 中根本不使用我的自定义格式,而是使用 AVAudioConverter 从我的水龙头中的硬件速率进行转换。 (未设置缓冲区的长度,无法判断结果是否正确)

这是针对 iOS 12.3.1 的。

关于iOS/swift : Record audio with 16khz on every hardware using AVAudioEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49370169/

相关文章:

ios - UISegmentedControl 取消选择在代码中无法识别,尽管它在视觉上是

xcode - "Run Script"在构建阶段需要什么权限?

IOS NSMethodSignature 保持为零

iOS 8 自定义单元格 : this class is not key value coding-compliant for the key description. '

ios - 如何将 iOS 应用程序转换到更多国家/地区的商店

swift - 如何在 Xcode macOS Cocoa 应用程序中嵌入和流式传输来自网络的视频?

iOS Objective C 在 View Controller 之间传递数据

ios - 有效负载安装顺序是否未定义?

ios - 当 SLComposeViewController 加载时,它会旋转到设备方向,即使我已将 Main UIViewController 固定为 Portrait

objective-c - 在 Objective C header 中访问 Swift 类