skip to Main Content

So I am trying to make a volume switcher that I can use by pressing UP and DOWN arrow keys on my keyboard.

When I try and log the new volume it has to be set to, this works fine, it gives me the correct value, but then when I try to set my volume on the <audio> element it does not appear to be working.

Below is my HTML Code:

        <audio id="music" controls autoplay>
            <source src="" type="audio/mpeg">
        </audio>

The src for the <source> element gets set in a different javascript, it will grab a random audio file.

Below here is my Javascript code:

let music_element = document.getElementById("music");

function setVolume(volume) {
    music_element.volume = volume;
}

function getVolume() {
    var volume = music_element.volume;
    return volume;
}


document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 38:
            var current_volume = getVolume();
            var new_volume = current_volume + 0.1;
            if (new_volume > 1) {
                new_volume = 1;
            }
            setVolume(new_volume.toFixed(1))
            console.log('Set volume to ' + new_volume.toFixed(1));
            break;
        case 40:
            var current_volume = getVolume();
            var new_volume = current_volume - 0.1;
            if (new_volume < 0) {
                new_volume = 0;
            }
            setVolume(new_volume.toFixed(1))
            console.log('Set volume to ' + new_volume.toFixed(1));
            break;
    }
};

Console Output when pressing UP and Down array

Any help/feedback would be highly appreciated!

2

Answers


  1. It is working for me, here’s a snippet you could have used in your question. Only difference is the part that sets the src to the music_element. Test if that part works for you.

    let music_element = document.getElementById("music");
    
    function setVolume(volume) {
      music_element.volume = volume;
    }
    
    function getVolume() {
      var volume = music_element.volume;
      return volume;
    }
    
    
    document.onkeydown = function(e) {
      switch (e.keyCode) {
        case 38:
          var current_volume = getVolume();
          var new_volume = current_volume + 0.1;
          if (new_volume > 1) {
            new_volume = 1;
          }
          setVolume(new_volume.toFixed(1))
          console.log('Set volume to ' + new_volume.toFixed(1));
          break;
        case 40:
          var current_volume = getVolume();
          var new_volume = current_volume - 0.1;
          if (new_volume < 0) {
            new_volume = 0;
          }
          setVolume(new_volume.toFixed(1))
          console.log('Set volume to ' + new_volume.toFixed(1));
          break;
      }
    };
    <h3>use arrow keys</h3>
    <audio id="music" controls autoplay>
        <source src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Mains_hum_60_Hz.ogg" type="audio/mpeg">
    </audio>
    Login or Signup to reply.
  2. It appears that your code is fine, a more likely reason that you have no sound is that you might have sound blocked by the browser. In Chrome do the following:

    1. Open the menu and click "Settings".
    2. Next click "Privacy and security".
    3. Then click "Site settings".
    4. Click "Additional content settings".
    5. Finally click "Sound" (see screenshot below)

    enter image description here.

    ✼ There is a minor discrepancy in that .keyCode property is deprecated. Use .key instead. (see Example)

    Details are commented in example

    // Reference <audio>
    const player = document.querySelector("#player");
    
    // Bind the "keydown" event to the Document Object
    document.onkeydown = setVolume;
    
    // "keydown" event handler passes the (event) Object by default
    function setVolume(event) {
      /*
       * Get the volume of audio#player and multiply it by 10 so
       * it's a whole number which is easier to increment.
       */
      let vol = player.volume * 10;
      /*
       * Event Object .key property will return a string that 
       * represents the key clicked on the keyboard.
       * Increment/decrement "vol" accordingly.
       */
      if (event.key === "arrowUp") {
        vol++;
      }
      if (event.key === "arrowDown") {
        vol--;
      }
      /*
       * If "vol" is less than 0 return 0
       * else if "vol" is greater than 1 return 1
       * otherwise return the original number.
       */
      vol = vol < 0 ? 0 : vol > 1 ? 1 : vol;
      // Multiply "vol" by .1 to keep it within a range of 0 to 1
      player.volume = vol * .1;
    }
    <audio id="player" src="http://soundbible.com/mp3/chinese-gong-daniel_simon.mp3" controls auto></audio>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search