admin管理员组文章数量:1287648
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>
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?
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>
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?
Share Improve this question asked May 13, 2017 at 22:39 GraceGrace 211 gold badge1 silver badge2 bronze badges 1- im not sure what you are talking about but maybe this helps stackoverflow./questions/12578379/… – momom Commented May 13, 2017 at 22:50
3 Answers
Reset to default 7You should do it like this.
First, create an audio object and hide it:
<audio id="audio" controls style="display:none">
<source src="http://butlerccwebdev/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:
document.addEventListener('keydown', function(e) {
if (e.keyCode == 65) {
document.getElementById('audio').play();
}
});
https://jsfiddle/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
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();
}
}
})
本文标签: audioHow to play a sound on key press in JavaScriptStack Overflow
版权声明:本文标题:audio - How to play a sound on key press in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741316303a2371935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论