Implementing .mp3 sound files in your JavaScript project

Arslan Ali
2 min readFeb 26, 2021

--

For my JavaScript project that I was doing for the Flatiron School, I decided to make an interactive piano. To my disappointment (or relief?), it seemed that the internet was already populated with many different pianos powered by different languages. Being a shaky junior developer, this encouraged me to continue down this path to see if I could come close to meeting some of the standards passed down by these coding legends.

When working on a JavaScript single-page application, your file structure should include a folder called assets. Going along with what Ruby taught me in terms of the separation of concerns, I divided my JavaScript, CSS, and HTML files into their own respective folders. When working on designing an instrument, arguably the most important aspect is the sound the instrument will play. Under assets I created sounds and in there were three additional folders with the names of each type of piano Sound I wanted to play; Grand Piano, Saw Synth, and Voice. Each of these would be populated with .mp3 files of the sounds that belongs to notes of that piano.

The idea was to ultimately iterate over each of these files as a PATCH request whenever the user wanted to select a new type of piano. On the coding front end side of things, this required a switch function to properly identify and utilize the keys when clicked.

keyboard = document.querySelector(".keyboard");keyboard.addEventListener("click", (event) => {
event.preventDefault();
const { id } = event.target;
switch (id) {
case "c":
c.play();
break;
case "cSharp":
cSharp.play();
break;
case "d":
d.play();
break;
case "dSharp":
dSharp.play();
break;
case "e":
e.play();
break;
case "f":
f.play();
break;
case "fSharp":
fSharp.play();
break;
case "g":
g.play();
break;
case "gSharp":
gSharp.play();
break;
case "a":
a.play();
break;
case "aSharp":
aSharp.play();
break;
case "b":
b.play();
break;
default:
null;
}
});

Ultimately this very simple invoking of the .mp3 files using the .play method allowed for my application to render unique sounds based on the HTML/CSS/JavaScript written into the program. I hope you enjoyed reading and learned something from my discoveries. Sound is a very important part of the online experience and implementing it correctly can be a powerful tool in your coding arsenal. Good luck in your continued journey as a coder.

--

--