skip to Main Content

I need to play a drum according to the key pressed on my keyboard. The only things that I’ve done is make it play when I click with the mouse.

I tried to add the function that plays the sounds of the drum according with to key of the keyboard, but I didn’t manage it.

function playKey(idKey) {
  const element = document.querySelector(idKey);
  if (element) {
    element.play();
  } else {
    console.error('element nof found')
  }
}

const btns = document.querySelectorAll('.btn')
for (i = 0; i < btns.length; i++) {
  const key = btns[i];
  const keyCode = key.classList[1];
  const idKey = `#btn-${keyCode}`;

  key.onclick = function() {
    playKey(idKey);
  }
}

2

Answers


  1. You can dispatch the event on key press and subscribe to the event to perform different actions. Which in your case might be playing different audio based on key.

    You can dispatch event by for e.g. this:

    document.dispatchEvent(new KeyboardEvent(‘keypress’, {‘key’: ‘H’}));

    Login or Signup to reply.
  2. I assume you want to play different audio when different keys are pressed and for that you can use keydown event to track key presses and also know which key was pressed.

    Here in the below code snippet we can catch which key was pressed. And then based on that you can play different audio as per your requirement.

    document.addEventListener('keydown', (event) => {
      const key = event.key.toLowerCase();
      console.log(key);
    // Play audio as per requirement
    });
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Home</title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width" />
        <link rel="stylesheet" href="styles.css" />
        <script type="module" src="script.js"></script>
      </head>
      <body>
        <h3>Hi</h3>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search