Strange count when increasing the audio volume in JavaScript

Viewed 180

I have one file HTML just to test play/pause and increase/decrease volume with event listeners in JavaScript. I can't exactly describe the anomaly i'm experiencing. I'm sure there is a logical explanation, but I can't wrap my head around it.

Basically, up and down arrow keys change the volume of the audio. But when I press the keys in some sort of a pattern like - up, up, down, down, up, down, up, down - the count does not follow any mathematical rules :D instead of increasing the volume, it gets decreased by specified value and vice versa.

I'm sure if you are answering this, you know how to, but to test it, just change the name of audio file inside src and drop the same file in the project. Then just load the HTML locally in the browser of your choice and debug it. The current volume will be displayed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Audio API</title>
</head>
<body>
<audio>
    <source src="njaar.mp3" type="audio/mpeg">
</audio>

<p id="currentVolume"></p>

<script>
    var audio;
    window.addEventListener('load', init, false);
    window.addEventListener("click", playPause, false);
    window.addEventListener("keydown", changeVolume, false);
    function init() {
        audio = document.getElementsByTagName('audio')[0];
        audio.play();
    }
    function playPause() {
        if (audio.paused) {
            audio.play();
        } else {
            audio.pause();
        }
    }
    function changeVolume() {
        document.getElementById("currentVolume").innerHTML = audio.volume;
        // if (audio.volume === 1) {
        //     document.getElementById("currentVolume").innerHTML = audio.volume;
        // }
        if (event.key === "ArrowUp") {
            try {
                audio.volume = audio.volume + 0.05;
            } catch (e) {
                console.error("Exception: " + e + "has been caught!");
            }
        }
        if (event.key === "ArrowDown") {
            try {
                audio.volume = audio.volume - 0.05;
            } catch (e) {
                console.error("Exception: " + e + "has been caught!");
            }
        }
        if (audio.volume < 0.05) {
            audio.volume = 0;
        }
    }
</script>
</body>
</html>

2 Answers

I think it's about the position of

document.getElementById("currentVolume").innerHTML = audio.volume;

You call it at the beginning of the function. That way you show the last update and not the current one.

Put it to the end of the function.

Tips:

  • add the event as a parameter
  • think about using += and -=

i had tested your code in my browser firefox 76.0.0. firefox block audio by default, i give it the permission and it worked fine. image description here]1

Related