0

i have been trying to add event listeners to keyboard so when respective keys are pressed a sound is made but the code that i have written is not working properly i have been trying to add event listeners to keyboard so when respective keys are pressed a sound is made but the code that i have written is not working properly

// Detecting keyboard press
document.addEventListener('keydown',function(event){
makeSound(event.key);
});


//  detecting which key is pressed and producing subsequent tune
  function makeSound(key)
{
switch (key) {
    case "w":
          var tom1 = new Audio("sounds/tom-1.mp3");
          tom1.play() ;
          break;
    case "a":
          var tom2 = new Audio("sounds/tom-2.mp3");
          tom2.play() ;
          break;
   case "s":
          var tom3 = new Audio("sounds/tom-3.mp3");
          tom3.play() ;
          break;
   case "d":
          var tom4 = new Audio("sounds/tom-4.mp3");
          tom4.play() ;
          break;
   case "j":
          var snare = new Audio("sounds/snare.mp3");
          snare.play() ;
          break;
   case "k":
          var kickbass = new Audio("sounds/kick-bass.mp3");
          kickbass.play() ;
          break;
   case "l":
          var crash = new Audio("sounds/crash.mp3");
          crash.play() ;
          break;

    default: console.log(buttonInnerHTML)
        break;
       }}
  • 1
    "is not working properly" is not enough on Stackoverflow. You need to include some debugging details: Is the function executed at all? Do you have any error in browser console? etc... – T.Trassoudaine Mar 16 '22 at 16:07
  • 1
    @Himanshu your code seems to work fine for me. Please check the path of your audio files. I have tried with an online mp3 file and it's working. Checkout the JSFiddle link : https://jsfiddle.net/shalinimandal/fxoc5asL/2/ – shalini mandal Mar 16 '22 at 16:08

0 Answers0