Volume Fader

  

 

    

Fade Time:  seconds



This page demonstrates a way to give a user control over the volume of a sound. Normally volume is controlled with a knob (dial) or a fader (slider). The HTML element <input> with type="range" is the easiest way to put a slider in your web page. The volume property of an <audio> element can have a value from 0 (silence) to 1 (full volume). In this example, the range of the slider is 0 to 100 (the default), and in JavaScript we simply multiply its value by 0.01 (same as dividing by 100) to map its value to the 0-to-1 range of volume. (An exponential mapping might make for a more natural sense of loudness variation.) 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