如何在按下特定键时播放声音 [英] How to play a sound when pressing a specific key

查看:132
本文介绍了如何在按下特定键时播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在按下 b 键时发出声音,但我似乎无法找出结果

HTML:

 < audio id =music> 
< source src =asap.mp3type =audio / mpeg>
< / audio>

JS:

  var s2 = document.getElementById('music')

document).keydown(function(e){
if(e.keyCode == 66){
s2.play();
}
});


解决方案

  

暂停< / p><! - 创建音频元素并用css隐藏它:display:none - >< audio id =audiocontrols style =display:none> < source src =http://butlerccwebdev.net/support/html5-video/media/soundfile.mp3type =audio / mpeg>您的浏览器不支援音讯元素。< / audio>


I'm trying to play a sound when I hit the b key, but i cant seem to figure it out

HTML:

<audio id="music">
  <source src="asap.mp3" type="audio/mpeg">
</audio>

JS:

var s2 = document.getElementById('music')

document).keydown(function(e){
  if (e.keyCode == 66) {
     s2.play();
        }
});

解决方案

//to play on the key A do this(using Jquery):
document.addEventListener('keydown', function(e) {
  if(e.keyCode == 66){
  document.getElementById('audio').play();
  }
  
  if(e.keyCode == 65){
  document.getElementById('audio').pause();
  }
});

<p>
press the "b" to play 
</p>
<p>
press the "a" to pause 
</p>

<!-- Create an audio element and hide it with css: display:none -->
<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>

这篇关于如何在按下特定键时播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆