0

I have a sound that is 2 seconds long. It is bound to the enter key. I want to be able to press the enter key multiple times per second enabling multiple layers of the same sound.

Currently I can initiate the sound, but the next one won't play until the first one is finished.

This is the code that I have that works but does not layer the sounds upon multiple keypresses:

         var fart = new Audio('http://www.soundjay.com/human/fart-01.wav');

         $(document).keydown(function(e) {
             if(e.keyCode == 13)
             {
              fart.play();
             }
         });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Click here then press enter.

This looked like it might contain the answer, but I wasn't able to get any executable code that worked for me: Sound effects in JavaScript / HTML5

Community
  • 1
  • 1
sjmartin
  • 3,662
  • 4
  • 15
  • 31

2 Answers2

1

The Audio.play method is not asynchronous. Thus your play() method 'waits' (blocks is the proper term) until it is finished before returning to the main loop.

Most JavaScript calls are blocking (and single threaded) so your application will usually wait for something to complete before going to the next line. To do something asynchronous in JavaScript, you'll need to call your function using something like setTimeout or setInterval.

Guru Evi
  • 174
  • 5
0

Adding this line will not create a new layer! But it will cause the audio file to be played again and again each time a key is pressed. No matter if 2 seconds have passed, it will start from the beginning each time.

var fart = new Audio('http://www.soundjay.com/human/fart-01.wav');

$(document).keydown(function(e) {
    if(e.keyCode == 13)
    {
        fart.play();
        fart.currentTime=0; // <- add this line
    }
});
54ka
  • 3,119
  • 2
  • 7
  • 21
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 11 '20 at 06:37