Create a Sound Board in 3 lines of code

Aneeqa Khan - Nov 7 '22 - - Dev Community

In this article, I'll show you how to create a Sound Board in JavaScript with only 3 simple lines of code.

Before that, create a bunch of buttons and style those quickly.

I have added 5 buttons for 5 different kinds of sounds.

  <div class="container">
    <div class="center">
      <button id="applause">applause</button>
      <button id="boo">boo</button>
      <button id="victory">victory</button>
      <button id="nope">nope</button>
      <button id="gasp">gasp</button>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode
.container {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
  width: 100px;
  height: 100px;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
button {
  min-width: 80px;
  height: 40px;
  margin-left: 10px;
  border-radius: 4px;
  border: 1px solid plum;
  cursor: pointer;
  color: purple;
  font-weight: 600;
}
Enter fullscreen mode Exit fullscreen mode

Now, I added the function to play the sound when a specific button is pressed.

  function play_sound(clicked_id) {
    var audio = new Audio(clicked_id + ".mp3");
    audio.play();
  }
Enter fullscreen mode Exit fullscreen mode

and call this function to a button onClick method

...
  <button id="applause" onClick="play_sound(this.id)">applause</button>
...
Enter fullscreen mode Exit fullscreen mode

That's it. You get a sound board with just 3 lines of code 🔊

Thank you for reading!
Feel free to connect on Twitter

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .