如何在JavaScript中的按键上播放声音? [英] How to play a sound on key press in JavaScript?
问题描述
我正在尝试编写JavaScript代码,以便仅在按下某个键时才播放声音.我尝试将其关联的HTML代码是:
I'm trying to write my JavaScript code so that a sound plays only when a certain key is pressed. The HTML code I am trying to associate it with is:
<div data-key="65" class="key">
<kbd>A</kbd>
<span class="sound">clap</span>
</div>
稍后在HTML文档中,数据键与音频文件相关联.我需要在JavaScript中进行设置,以便在按下"A"时可以播放声音.到目前为止,我已经尝试过:
The data key is associated with the audio file later in the HTML document. I need to set it up in JavaScript so that when 'A' is pressed it plays the sound. So far I have tried:
document.querySelector('65').addEventListener('onkeydown', function() {
playAudio ();
});
关于如何进行这项工作的任何想法?
Any ideas about how to make this work?
推荐答案
您应该这样做.
首先,创建一个音频对象并将其隐藏:
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>
然后为按键按下EventListener
并确保它是正确的键:
Then make an EventListener
for a keypress and assure it's the right key:
document.addEventListener('keydown', function(e) {
if (e.keyCode == 65) {
document.getElementById('audio').play();
}
});
https://jsfiddle.net/cwvfmLvk/6/
这篇关于如何在JavaScript中的按键上播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!