ness64
ness64

Reputation: 31

Playing sound by keypress using Javascript and HTML

I'm super new to web development, and I'm trying to get this simple example of an online drumkit working. The website loads fine, but when I press a key nothing happens. I know this is a very silly question, but I am a bit stumped. Thanks!

<!DOCTYPE html>
<html>
<body>

<h2>Simple Drumkit!</h2>
<p>C = Kick, A = Crash, Z and X = Snare!</p>

<script>
const sounds = {
  'KeyZ': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyX': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyA': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/crash1.ogg',
  'KeyC': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/kik.ogg'
}

const play = sound => {
  console.log("playing",sound)
  var audio = new Audio(sound);
  audio.play();
}

window.addEventListener('keypress', function(e) { console.log(e.code)
  if (sounds[e.code]) {
    console.log("clicking",e.code)
    document.getElementById(e.code).click()
  }  
})
</script> 

</body>
</html>

Upvotes: 0

Views: 92

Answers (1)

Bramhacharya Sushant
Bramhacharya Sushant

Reputation: 52

For me, I would use function and pass values and its works perfectly.

I am calling the function when the user presses the key and then that specific function plays sound. It has little latency in playback because of external links maybe.

<!DOCTYPE html>
<html>
<body>

<h2>Simple Drumkit!</h2>
<p>C = Kick, A = Crash, Z and X = Snare!</p>

<script>
    
const sounds = {
  'KeyZ': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyX': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyA': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/crash1.ogg',
  'KeyC': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/kik.ogg'
}

//Changed into function
function playSound(sound) {
  console.log("playing",sound)
  var audio = new Audio(sound);
  audio.play();
}

window.addEventListener('keypress', function(e) { console.log(e.code)
  if (sounds[e.code]) {
    console.log("clicking",e.code);

    // calling function and passing sounds[e.code] which is address as arguments
    playSound(sounds[e.code]);
  }  
})
</script> 

</body>
</html>

Upvotes: 1

Related Questions