-7

Can someone give me an example of how I can play a sound when the 'a' key is pressed (for example) with pure javascript. I've read similar questions, but people have always responded with jQuery codes

Iyves
  • 63
  • 5
  • 2
    Possible duplicate of [Simplest way to detect keypresses in javascript](https://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript) – Kos Jan 20 '18 at 16:44
  • 3
    Possible duplicate of [Play a sound when a key is pressed](https://stackoverflow.com/questions/12578379/play-a-sound-when-a-key-is-pressed) – GalAbra Jan 20 '18 at 16:44
  • 3
    You've asked the [same question 2 hours ago](https://stackoverflow.com/questions/48357436/how-to-play-a-sound-when-pressing-a-specific-key/48357494?noredirect=1#comment83701786_48357494)... O.o – Andreas Jan 20 '18 at 16:55

1 Answers1

1

I think you are looking for something like this:

index.html

<div data-key="65" class="key">
    <kbd>A</kbd>
</div>

<audio data-key="65" src="youraudiofile.wav"></audio>

app.js

window.addEventListener('keydown', function(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
    if (!audio) return;
    audio.currentTime = 0; // rewind to the start of audio
    audio.play();
    key.classList.add('playing')
});
Leafyshark
  • 395
  • 2
  • 5
  • 11