Search code examples
javascripthtmlaudiovolume

How to decrease the volume of an audio element, gradually by pressing a button


I am trying to figure out a way to incrementally lower the volume of audio in HTML using JavaScript. I would like to simply press a HTML button, and for that button to lower the volume of audio gradually, and for it to cut out upon reaching zero.

I have tried to find the answer to this problem online, but there are no resources out there on how to achieve this. Any help would be greatly appreciated.

This is my attempt at solving this problem in JavaScript;

var decreaseVolume
var birds = document.getElementById("$audio");

function rampdown(){
  var maxVolume = 100;
  decreaseVolume = setInterval(function(){
    if (maxVolume == 0) {
      clearInterval(decreaseVolume);
      birds.volume = "0";
    } else {
      birds.volume = rampdown;
    }
    rampdown -= 1;
  }, 30);

}

I have created a button in HTML with onclick="rampdown()", but it doesn't do anything to the volume. Any help would be greatly appreciated.


Solution

  • Volume is 0 to 1, not 0 to 100

    var decreaseVolume
    var birds = document.getElementById("$audio");
    console.log(birds.volume)
    
    function rampdown(){
      var maxVolume = 100;
      decreaseVolume = setInterval(function(){
        if (maxVolume == 0) {
          clearInterval(decreaseVolume);
          birds.volume = "0";
        } else {
          birds.volume = maxVolume/100;
        }
        maxVolume -= 1;
      }, 30);
    }
    <audio id="$audio" controls src="https://file-examples.com/storage/fef1706276640fa2f99a5a4/2017/11/file_example_MP3_700KB.mp3"></audio>
    <button id="reduce" type="button" onclick="rampdown()">reduce</button>