6

I'm looking for a way to tap into the current audio output on a Mac, then return a value representing the current sound level.

By sound level, I mean the amount of noise being generated by the output. I'm NOT asking how to get the current volume level of the output device.

Pétur Ingi Egilsson
  • 4,368
  • 5
  • 44
  • 72

1 Answers1

18

the following code is pulled from Apple's Sample AVRecorder … this particular bit of code acquires a set of connections from this class's movieFileOutput's connections methods, gets the AVCaptureAudioChannel for each connection, and calculates decibel power based upon that. i would presume that if you are looking for an output "noise level", you would be able to capture similar information. if you are looking for something lower level than this, try the HAL (Hardware Abstraction Layer) framework.

- (void)updateAudioLevels:(NSTimer *)timer
{
    NSInteger channelCount = 0;
    float decibels = 0.f;

    // Sum all of the average power levels and divide by the number of channels
    for (AVCaptureConnection *connection in [[self movieFileOutput] connections]) {
        for (AVCaptureAudioChannel *audioChannel in [connection audioChannels]) {
            decibels += [audioChannel averagePowerLevel];
            channelCount += 1;
        }
    }

    decibels /= channelCount;

    [[self audioLevelMeter] setFloatValue:(pow(10.f, 0.05f * decibels) * 20.0f)];
}
john.k.doe
  • 7,533
  • 2
  • 37
  • 64
  • 1
    Shouldn't that conversion be pow(10.f, 0.05f * decibels)? you don't need that extra times 20 there. read here: http://stackoverflow.com/questions/2465328/iphone-sdk-avaudiorecorder-metering-how-to-change-peakpowerforchannel-from-d or better yet http://travisjeffery.com/b/2013/02/converting-avfoundations-power-levels-to-from-logarithmic-and-linear-scale/ – ucangetit May 02 '14 at 10:18
  • @ucangetit, i can't speak intelligently to that bit of detail regarding the code snippet. i only copied the code in case Apple revised the link to the sample code. – john.k.doe May 02 '14 at 21:30