Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Audio Api working with Decibels

I wish to understand how to work with decibels in Web Audio API

Here i have an audio buffer connected to a gain node

var mybuffer = context.createBufferSource());
mybuffer.buffer = buffer; //an audio buffer

var gainNode=context.createGain();

mybuffer.connect(gainNode);
gainNode.connect(context.destination);

Gain volume is a range from 0(silent) to n where 1 is the default volume but as i know, usually audio is not related to such a range, its volume is measured in decibels (Db) and operations are made in Db too.

I have read something interesting in this answer but it's far to be complete for my needs: Is there a way get something like decibel levels from an audio file and transform that information into a json array?

I wonder how to determine decibel for an Audio Node, how to edit volume using decibels

like image 800
Mike Avatar asked Mar 24 '14 08:03

Mike


1 Answers

Decibels are an interesting beast. Decibels aren't really a measure of volume, per se - they're a measure of gain or attentuation, as described in http://en.wikipedia.org/wiki/Decibel. The number of decibels is ten times the logarithm to base 10 of the ratio of the two power quantities.

You can get decibels out of one critical place in the Web Audio API - the RealtimeAnalyser's getFloatFrequencyData returns a float array of attenuation per frequency band, in decibels. It's not technically volume - but it's attenuation from unity (1), which would be a sine wave in that frequency at full volume (-1 to 1).

Gain controls are, of course, commonly expressed in decibels, because they're a measure of a ratio - between unity and whatever your volume knob is set to. Think of unity (0 dB, gain=1) as "as loud as your speakers will go".

To express a gain in decibels, remember that a gain of 1 (no attenuation, no gain) would equal 0 decibels - because 10^0 = 1. (Actually - it's because 10 ^ (0/10) = 1. Obviously, zero divided by anything is still zero - but remember, these are DECI-bels, there's a factor of ten in there.) The aforementioned Wikipedia article explains this in good depth.

To convert between the two - e.g., to set a gain.value when you have decibels, and to get the decibel gain from gain.value - you just need to use the formula

decibel_level = 20 * log10( gain.value );

aka

gain.value = Math.pow(10, (decibel_level / 20));

Note that base 10 log is a little more complex in Javascript, due to only having access to the natural logarithm, not the base 10 logarithm - but you can get that via

function log10(x) {
    return Math.log(x)/Math.LN10;
}

(There's a Math.log10() method, but it's experimental and not implemented across all browsers.)

like image 73
cwilso Avatar answered Nov 20 '22 15:11

cwilso