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
Add a ment  | 

3 Answers 3

Reset to default 7

You 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