-4

Hi I am new javascript and in need of some code. I would like some code that when the user presses the key "c" a sound file called sound1.mp3 plays and then the user presses the key "y" another sound file called sound2.mp3 plays.

Thanks

Thomas

  • Do you know how to handle keyboard events and just need help playing audio? Or are you asking about both detecting keyboard events and playing audio? – Ted A. Mar 12 '16 at 23:33
  • 1
    http://stackoverflow.com/questions/9419263/playing-audio-with-javascript will show you how to play the audio files. If you're asking people to write a complete script for you from scratch that's not really what SO is about... – Ted A. Mar 12 '16 at 23:37

1 Answers1

0

Well, I can't really say you provided a lot of information, but with what you wrote this is the best I could come up with.

I am assuming you don't have a lot of experience with js, so I will do my best to explain what I have done here.

First I am registering an event handler on the document object, which means that it will call a function with the event (e). The anonymous function will then assign the top-level variable audio to a new Audio object with whatever file you want, and after that it will play it.

Feel free to ask any questions you might have.

var audio;

document.onkeypress = function (e) {
  switch(e.key) {
    case "c":
      audio = new Audio("sound1.mp3");
      break;
    case "y":
      audio = new Audio("sound2.mp3");
      break;
  }

  audio.play();
};
Fredrik
  • 971
  • 8
  • 23