0
    $(document).on('keydown', function(event) {
            const current = audios[Number(event.key) // audios is array of music files
            current.currentTime = 0;
            current.play();
    });

I'm creating a drum application. If I press the number 2 with the keydown event, it will be activated. And while I hold down the number 2 and press 3, the number 2 will stop sounding. How can I make it happen? And Why do not this?

codingme
  • 11
  • 4

1 Answers1

0

It looks like there's a syntax error in your code. const current = audios[Number(event.key) is missing a closing ].

Here is how I would approach it.

const pressedKeys = {};

$(document.body).keydown(function (evt) {
  pressedKeys[Number(evt.key)] = true;
  playSongs(pressedKeys);
});

$(document.body).keyup(function (evt) {
  pressedKeys[Number(evt.key)] = false;
});

function playSongs(dict) {
  for (let song in dict) {
    if (dict[song] === true) {
      audios[song].currentTime = 0;
      audios[song].play();
    }
  }
}

This code keeps track of keys in a dictionary. Whenever a keydown is registered it adds it to the dictionary. Right afterwards, playSongs finds all keys that are true and plays that song.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33