Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - How to play a sound when pressing a specific key

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();
        }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

//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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...