Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...