2

I want to be able to play a mp3 file when the tab key is pressed on a keyboard.

I am making a number system for a restaurant and when a number is entered and tab is pressed, it will make a noise which will draw attention to the numbers.

Thanks!

My current code is this. It doesn't work... Please correct me!

    <script>
      window.addEventListener("keydown", checkKeyPressed, false);

      function checkKeyPressed(e) {
        if (e.keyCode == "9") {
          //Play Music
          document.getElementById('aud').play()
        } 
      }
    </script>
    <audio src="music.mp3" id="aud">
      <p>Your browser does not support the audio element.</p>
    </audio>

I also made it hidden in css and the music file is in the same folder... It is not working...

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315

1 Answers1

3

Try using Javascript Keyboard Events using addEventListener in Javascript. The keyCode "9" represents the tab key.
Examples are shown at this webpage: http://www.kirupa.com/html5/keyboard_events_in_javascript.htm
Javascript:

window.addEventListener("keydown", checkKeyPressed, false);

function checkKeyPressed(e) {
    if (e.keyCode == "9") {
        //Play Music
        document.getElementById('yourAudioTag').play()
    }
}

HTML: For playing the music, it's easy if you create an <audio> element like this:

<audio src="dingdong.mp3" id="yourAudioTag">
<p>Your browser does not support the audio element.</p>
</audio>


CSS: add the property display: none; so that it isn't visible to the user.

#yourAudioTag
{
display: none;
}


JS Event Listener: document.getElementById('yourAudioTag').play();

Henry Zhu
  • 2,488
  • 9
  • 43
  • 87
  • What is the first line of code? I get the function but not the first line.. This is a great start though. – ValveRewards Jan 22 '15 at 01:22
  • Read my edited response above on the event listener. Please check my response if you accept it so that others can view it. Thanks. – Henry Zhu Jan 22 '15 at 01:30
  • I can play music by? the video file name will be dingdong.mp3. Would I place this code in the //Play Music section? How will I put this code in there? – ValveRewards Jan 22 '15 at 01:37
  • Reread the HTML section. I suggest you create an audio tag with your music path in it, and use JS to target the element's id as I showed in the Javascript Section of my response (Yes, in the //Play Music section) – Henry Zhu Jan 22 '15 at 01:42
  • btw, do i have to connect jquery? Does this function use jquery or is it plain javascript? I do not have jquery connected... – ValveRewards Jan 22 '15 at 01:54
  • It's obviously plain javascript. – Henry Zhu Jan 22 '15 at 02:13