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
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
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();
};