我如何指定AVAudioEngine Mic-Input的格式?

我想用AVAudioEngine和用户麦克风录制一些audio。 我已经有一个工作示例,但只是无法弄清楚如何指定我想要的输出格式…

我的要求是,我需要AVAudioPCMBuffer因为我现在正在说话…

我需要添加一个单独的节点,做一些转码? 我找不到有关这个问题的很多文档/样本。

而Audio-Stuff也是一个小菜鸟。 我知道我希望NSData包含PCM-16bit最高采样率16000(8000会更好)

这是我的工作示例:

 private var audioEngine = AVAudioEngine() func startRecording() { let format = audioEngine.inputNode!.inputFormatForBus(bus) audioEngine.inputNode!.installTapOnBus(bus, bufferSize: 1024, format: format) { (buffer: AVAudioPCMBuffer, time:AVAudioTime) -> Void in let audioFormat = PCMBuffer.format print("\(audioFormat)") } audioEngine.prepare() do { try audioEngine.start() } catch { /* Imagine some super awesome error handling here */ } } 

如果我改变格式让我们说

 let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatInt16, sampleRate: 8000.0, channels: 1, interleaved: false) 

那么如果将产生一个错误说,采样率需要是相同的hwInput …

很感谢任何forms的帮助!!!

编辑:我刚刚findAVAudioConverter但我需要兼容iOS8以及…

您不能直接在input和输出节点上更改audio格式。 在麦克风的情况下,格式将始终为44KHz,1通道,32位。 为此,您需要在两者之间插入混音器。 然后当你连接inputNode> changeformatMixer> mainEngineMixer时,你可以指定你想要的格式的细节。

就像是:

 var inputNode = audioEngine.inputNode var downMixer = AVAudioMixerNode() var mainMixer = audioEngine.mainMixerNode //I think you the engine's I/O nodes are already attached to itself by default, so we attach only the downMixer here: audioEngine.attachNode(downMixer) //You can tap the downMixer to intercept the audio and do something with it: downMixer.installTapOnBus(0, bufferSize: 2048, format: downMixer.outputFormatForBus(0), block: //originally 1024 { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in print(NSString(string: "downMixer Tap")) do{ print("Downmixer Tap Format: "+self.downMixer.outputFormatForBus(0).description)//buffer.audioBufferList.debugDescription) }) //let's get the input audio format right as it is let format = inputNode.inputFormatForBus(0) //I initialize a 16KHz format I need: let format16KHzMono = AVAudioFormat.init(commonFormat: AVAudioCommonFormat.PCMFormatInt16, sampleRate: 11050.0, channels: 1, interleaved: true) //connect the nodes inside the engine: //INPUT NODE --format-> downMixer --16Kformat--> mainMixer //as you can see I m downsampling the default 44khz we get in the input to the 16Khz I want audioEngine.connect(inputNode, to: downMixer, format: format)//use default input format audioEngine.connect(downMixer, to: audioEngine.outputNode, format: format16KHzMono)//use new audio format //run the engine audioEngine.prepare() try! audioEngine.start() 

不过,我会推荐使用一个开放的框架,如EZAudio。

您不能更改input节点的configuration,尝试使用所需的格式创build混合节点,将其附加到引擎,然后将其连接到input节点,然后将mainMixer连接到刚刚创build的节点。 现在你可以在这个节点上安装一个tap来获取PCM数据。

请注意,由于一些奇怪的原因,您没有太多的采样率select! 至less不在iOS 9.1上,请使用标准11025,22050或44100.任何其他采样率都将失败!