简体   繁体   English

当我按下键盘上的“ z”时,我希望它将具有sound1.wav的键“ a”更改为现在按下时播放sound2.wav

[英]When I press a 'z' on the keyboard I want it to change the key “a” that had sound1.wav to now play a sound2.wav when pressed

So what I'm trying to accomplish is this: Pressing 'a' on keyboard plays 'hello.wav'. 所以我要完成的是:在键盘上按'a'会播放'hello.wav'。 Pressing 'z' on keyboard changes the key 'a' to 'goodbye.wav'. 按键盘上的“ z”将键“ a”更改为“ goodbye.wav”。 Now by pressing 'a' on keyboard it plays this 'goodbye.wav' instead of 'hello.wav'. 现在,通过在键盘上按“ a”,它将播放此“ goodbye.wav”而不是“ hello.wav”。

So in html I have a div of a bunch of audio id: 因此,在html中,我有一堆音频ID的div:

            <audio id="c1" controls style="display:none">
              <source src="hello.wav" type="audio/mpeg">
            </audio>

and to trigger the sound is by pressing the key "a" which is keycode=65 and the javascript code is: 并通过按下按键“ a”(按键代码= 65)和javascript代码来触发声音:

    document.addEventListener('keydown', function(e) {
      if (e.keyCode == 65) {
        document.getElementById('c1').play();
      }
    });

What I don't know how to do is that if I pressed key "z" then keycode == 65 would now play goodbye.wav instead of hello.wav: 我不知道该怎么做,如果我按了键“ z”,那么键码== 65现在将播放goodbye.wav而不是hello.wav:

     <audio id="ex1" controls style="display:none">
          <source src="goodbye.wav" type="audio/mpeg">
    </audio>

You could track if z was pressed using some flag, and on A key, play the approrpiate music. 您可以使用某些标志来跟踪z是否被按下,然后在A键上播放适当的音乐。 Hope I've understood your requirement correctly. 希望我正确理解了您的要求。

var enableGoodbye = false;
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 65) {
    if (enableGoodbye === true)
        document.getElementById('ex1').play();
    else
        document.getElementById('c1').play();
  } else if (e.keyCode == 90) { //If Z, set flag to true
        enableGoodbye = true;
  }
});

Here is a fiddle: http://jsfiddle.net/t8owxqo6/ 这是一个小提琴: http : //jsfiddle.net/t8owxqo6/

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

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