简体   繁体   English

如何在 JavaScript 按键时播放声音?

[英]How to play a sound on key press in JavaScript?

I'm trying to write my JavaScript code so that a sound plays only when a certain key is pressed.我正在尝试编写我的 JavaScript 代码,以便仅在按下某个键时才会播放声音。 The HTML code I am trying to associate it with is:我试图关联的 HTML 代码是:

<div data-key="65" class="key">
  <kbd>A</kbd>
  <span class="sound">clap</span>
</div>

The data key is associated with the audio file later in the HTML document.数据密钥与稍后在 HTML 文档中的音频文件相关联。 I need to set it up in JavaScript so that when 'A' is pressed it plays the sound.我需要在 JavaScript 中进行设置,以便在按下“A”时播放声音。 So far I have tried:到目前为止,我已经尝试过:

document.querySelector('65').addEventListener('onkeydown', function() {
playAudio ();
});

Any ideas about how to make this work?关于如何使这项工作有任何想法吗?

You should do it like this.你应该这样做。

First, create an audio object and hide it:首先,创建一个音频对象并隐藏它:

 <audio id="audio" controls style="display:none"> <source src="http://butlerccwebdev.net/support/html5-video/media/soundfile.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>
Then make an EventListener for a keypress and assure it's the right key: 然后为按键创建一个EventListener并确保它是正确的键:

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

https://jsfiddle.net/cwvfmLvk/6/ https://jsfiddle.net/cwvfmLvk/6/

After Some Minor Modifying You can use the specified key as a trigger for the Audio Clip一些小的修改后,您可以使用指定的键作为音频剪辑的触发器

  if (e.keyCode == 65) {
    if(document.getElementById('audio').paused){
    document.getElementById('audio').play();
   }
   else{
    document.getElementById('audio').pause;
  }
});

Here it will work as a trigger for the Audio file.. Credit: Andreas Moldskred在这里它将作为音频文件的触发器。信用:Andreas Moldskred

This might work for you.这可能对你有用。

var play=document.getElementById('play');
var music=document.getElementById('music1')
document.addEventListener('keydown',function(e){
    if(e.keyCode==65){
        if(music1.paused){
            music1.play();
        }
        else{
            music1.pause();
        }
    }
})

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

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