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

Geo*_*org 12 core-audio avfoundation ios avaudioengine

我想录制一些音频AVAudioEngine和用户麦克风.我已经有了一个工作样本,但是无法弄清楚如何指定我想要的输出格式...

我的要求是,我需要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 */ }
}
Run Code Online (Sandbox Code Playgroud)

如果我改变格式让'说'

let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatInt16, sampleRate: 8000.0, channels: 1, interleaved: false)
Run Code Online (Sandbox Code Playgroud)

然后如果会产生一个错误,说样本速率需要与hwInput相同...

很感谢任何形式的帮助!!!

编辑:我刚刚发现,AVAudioConverter但我需要兼容iOS8 ...

Jos*_*osh 13

您无法直接在输入节点或输出节点上更改音频格式.在麦克风的情况下,格式将始终是44KHz,1通道,32位.为此,您需要在两者之间插入一台调音台.然后,当您连接inputNode> changeformatMixer> mainEngineMixer时,您可以指定所需格式的详细信息.

就像是:

var inputNode = audioEngine.inputNode
var downMixer = AVAudioMixerNode()

//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()
Run Code Online (Sandbox Code Playgroud)

不过,我建议使用像EZAudio这样的开放式框架.

  • 您的`mainMixerNode`未使用.您将在示例中连接到`outputNode`.为什么? (3认同)