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
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’}));
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.