I am trying to build a drum kit web app in which a certain key is certain drum. When I’m playing two different sounds while the first one isn’t done it works fine, it’s just finishing both sounds and stops as it should do.
When I’m trying to play the third sound while the first two didn’t yet finished, it just scrambles them all and none are sounding as should be.
function playSound(event) { var keyPressed = event.keyCode; if (keyPressed === 65) { audio.hihat.currentTime = 0; audio.hihat.cloneNode(true).play(); } else if (keyPressed === 83) { audio.snare.currentTime = 0; audio.snare.play(); } else if (keyPressed === 81) { audio.crash.currentTime = 0; audio.crash.play(); } else if (keyPressed === 87) { audio.tom01.currentTime = 0; audio.tom01.play(); } else if (keyPressed === 69) { audio.tom02.currentTime = 0; audio.tom02.play(); } }
Advertisement
Answer
Javascript by default will only allow you to play one sound at a time, and will not play the next sound until it is registered as completed. To save yourself some footwork, the howler.js
library makes it very easy to solve the exact problem you’ve described.
Sounds can be used as the source of a howl
object. Here’s a snippet from their official documentation.
var sound = new Howl({ src: ['sound.mp3'] });
Then, your sound can be played like so.
sound.play();
Here is an example of a project which I utilized howler.js
to allow overlapping sounds. I believe this is the effect you are looking for with your drum kit.
Here’s how I laid it out in my app:
sound: new Howl({ src: ['Assets/bubbles.mp3'] })
Then, when I execute my event (which in my case is a key press), I call the howl.
function onKeyDown(event) { sound.play();
There’s some extra pieces I used in my project as I was also using the Paper.js
library as well, but I just wanted to give you the general idea of how howler.js
works without veering too far away from the scope of your question.
The official website where you can download howler.js
is here.