skip to Main Content

Im trying to make this audio play when a specific key is pressed and will continue to loop. Any ideas on how to make this work?

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
<audio controls loop>
    <source src="Chiptronical.ogg" type="audio/ogg">
    </audio>
  }
});

i wanted it to play the audio when the key is pressed but it just doesnt work

2

Answers


  1. try this and run on browser. and press enter.
    make sure directory is same with audio file

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script>
        $(document).ready(function(){
        
        document.addEventListener("keypress", function(event) {
      if (event.keyCode == 13) {
        
            $('body').append( `<audio controls autoplay>
      <source src="Chiptronical.ogg" type="audio/ogg">
      <source src="Chiptronical.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
    </audio>` );
     }
    });
    
    
        });
        </script>
    </head>
    
    <body>
    
    <h1>The audio autoplay attribute</h1>
    
    <p>Press Enter to play a sound:</p>
    
    </body>
    </html>
    
    Login or Signup to reply.
  2. You can achieve the desired results like this:-

    Here is the html:-

    <audio id="audioElement" controls loop>
        <source src="Chiptronical.ogg" type="audio/ogg">
    </audio>
    

    Here is the JavaScript:-

    const audioElement = document.querySelector('#audioElement');
    document.addEventListener("keypress", function(event) {
      if (event.keyCode == 13) {
          // For Play
          audioElement.play();
          // For Pause
          audioElement.pause();
    
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search