简体   繁体   English

按键发出声音?

[英]Press key for sound?

Hi I am new javascript and in need of some code.嗨,我是新的 javascript,需要一些代码。 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.我想要一些代码,当用户按下“c”键时,会播放一个名为 sound1.mp3 的声音文件,然后用户按下“y”键时会播放另一个名为 sound2.mp3 的声音文件。

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.我假设你对 js 没有很多经验,所以我会尽力解释我在这里所做的。

First I am registering an event handler on the document object, which means that it will call a function with the event ( e ).首先,我在document对象上注册一个事件处理程序,这意味着它将使用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.然后匿名函数会将顶级变量audio分配给一个新的Audio对象,其中包含您想要的任何文件,之后它将播放它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM