0

I have a small problem, I made a piano using JavaScript in the browser and it's working with the keyboard keys. i need only javascript, jquery is not an option for me right now.

The issue is when I hold a key, the noise sound keeps on repeating itself and I want it to play only once per key I press even when I hold it for couple of seconds.

How can I do that?

<audio id="do"> 
<source src="do.mp3" type="audio/mp3"></audio>


<script>

    var do1 = document.getElementById('do');

    function load1()
    {
        do1.load();
    }

    document.addEventListener('keydown',function(event) {
        if(event.keyCode == 90) {{do1.load()
            do1.play();
        }}

    });
</script>
kshayk
  • 85
  • 1
  • 8

1 Answers1

0

Add a flag on the first key press (key down event), that is reset on the key up event and prevents subsequent key down events from triggering multitple times without releasing the key in the meanwhile.

var prevent = false;

document.addEventListener('keydown',function(event) {
    if(event.keyCode == 90 && !prevent) {
        prevent = true;
        do1.load()
        do1.play();
    }
});

document.addEventListener('keyup',function(event) {
    prevent = false;
});

However, an issue might be that the keyup event might not be received when the focus was set elsewhere before releasing a key. I'm not aware that there are any capture-key mechnisms available to prevent that...

fast
  • 885
  • 7
  • 15