Volume Fader in Decibels

  

 

    

Fade Time:  seconds



This page demonstrates a way to give a user control over the volume of a sound with a fader (a.k.a. a slider). The HTML element <input> with type="range" is the easiest way to put a slider in your web page. In this example, the range of the slider is 0 to 100 (the default), and the volume property of an <audio> element can have a value from 0 (silence) to 1 (full volume). To make the change in the slider correspond well to our subjective sense of loudness, in JavaScript we need to map the slider value to the 0-to-1 range of volume using an exponential mapping. (Our subjective sense of loudness is proportional to the logarithm of the amplitude, so in order to have a linear sense of change in loudness, the change in amplitude should follow an exponential curve.) So as the slider goes from 100 down to 1, we change the volume from 0 dB down to -49.5 dB in increments of 0.5 decibel. When the slider is at 0, instead of going to -50 dB, which is very soft but not totally off, we simply set the volume to 0 (which would be -INF dB). Note that we use the "oninput" event of the slider for continual updating every time the user moves the slider to a different value, rather than the "onchange" event, which occurs only once when the user releases the slider.

The page also demonstrates a way to do a timed fade-in or fade-out, using the setInterval() method in JavaScript. The method allows you to specify a function you want to occur repeatedly at regular intervals. The minimum interval between repetitions is 10 milliseconds. For a slider with 100 steps, we can therefore pass through every single step in as little as one second. For a fade-out, we move the slider down from its current value to 0 in increments that are 1/100 of the specified fade time. (The fade time is specified by the user in seconds, whereas setInterval() expects an interval to be specified in milliseconds.) We also store the user's setting of the volume slider so that we can fade back to that value for a fade-in. When we reach the destination, we stop the setInterval() method with clearInterval().


This page was last modified April 14, 2021 by
Christopher Dobrian dobrian@uci.edu