Create a Sound Board in 3 lines of code
Aneeqa Khan
Posted on November 7, 2022
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>
.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;
}
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();
}
and call this function to a button onClick method
...
<button id="applause" onClick="play_sound(this.id)">applause</button>
...
That's it. You get a sound board with just 3 lines of code 🔊
Thank you for reading!
Feel free to connect on Twitter
💖 💪 🙅 🚩
Aneeqa Khan
Posted on November 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.