在OSX中以编程方式更改麦克风增益

时间:2013-02-27 16:37:24

标签: macos cocoa core-audio audioqueue

我在OSX 10.8

在我的应用程序中,我不得不改变Mic增益,我使用AudioQueue来捕获缓冲区,但没有获得任何改变Mic增益的指针,

Apple HAL文档也有,但没有得到任何结果,

2 个答案:

答案 0 :(得分:0)

首先,向您的队列询问其kAudioQueueProperty_CurrentDevice,这是它正在读取的设备的标识符字符串。

接下来,您需要打开该设备。这是比它应该做的更多的工作,因为Core Audio的设计师相信通过通用的“GetProperty”和“SetProperty”功能来做任何事情。这是:

  1. 创建一个AudioValueTranslation结构,其中包含指向包含设备标识符的变量的指针,以及指向您希望AudioDeviceID的变量的指针。
  2. 使用AudioHardwareGetProperty或未弃用但更通用的AudioObjectGetProperty获取kAudioHardwarePropertyDeviceForUID,将指针传递给结构。 HAL将查找设备并通过您放入结构中的指针将其返回给您。
  3. 如果没有返回错误,您现在有了设备。

    最后一步是设定其增益。我认为这在输入范围内表现为kAudioDevicePropertyVolumeScalar,但我并不是100%肯定。无论如何,在找到合适的组合之前,您将修改AudioDeviceSetProperty和/或AudioObjectSetProperty

答案 1 :(得分:0)

看起来,当AudioQueue运行时,无法动态改变音量增益,有些人如何能够在缓冲区中添加Mic增益,发布代码,

void AQRecorder::setGain(void *data, int bytes, float gain){
    SInt16 *editBuffer = (SInt16 *)data;

    // loop over every packet

    for (int nb = 0; nb < (bytes / 2); nb++) {

        // we check if the gain has been modified to save resoures
        if (gain != 0) {
            // we need more accuracy in our calculation so we calculate with doubles
            double gainSample = ((double)editBuffer[nb]) / 32767.0;

            /*
             at this point we multiply with our gain factor
             we dont make a addition to prevent generation of sound where no sound is.

             no noise
             0*10=0

             noise if zero
             0+10=10
             */
            gainSample *= gain;

            /**
             our signal range cant be higher or lesser -1.0/1.0
             we prevent that the signal got outside our range
             */
            gainSample = (gainSample < -1.0) ? -1.0 : (gainSample > 1.0) ? 1.0 : gainSample;

            /*
             This thing here is a little helper to shape our incoming wave.
             The sound gets pretty warm and better and the noise is reduced a lot.
             Feel free to outcomment this line and here again.

             You can see here what happens here http://silentmatt.com/javascript-function-plotter/
             Copy this to the command line and hit enter: plot y=(1.5*x)-0.5*x*x*x
             */

            gainSample = (1.5 * gainSample) - 0.5 * gainSample * gainSample * gainSample;

            // multiply the new signal back to short
            gainSample = gainSample * 32767.0;

            // write calculate sample back to the buffer
            editBuffer[nb] = (SInt16)gainSample;
        }
    }
}

请记住,只有在增益发生变化时才应调用此函数,否则会节省CPU资源。