Summary
Here is a summary of what you need to introduce sounds into your game. Each part will be explained in more details below.
You will find an example of a game with sounds here. It might be a good idea to open this game in a separate tab and keep it there while you read this page. I will refer to it, and my code examples come directly from this game.
Sound Files
It may seem obvious but to play a sound in your game, you need to provide a sound file. For this game, you can find those online. Browsers are able to play a variety of sound file formats: MP3, OGG, AIFF, WAVE, etc. I recommend MP3/OGG for song level files, and WAVE/AIFF for clips.
There are many places online where you can find free sound clips, even whole background songs. Use a search engine. I give you some sites at the end. You can of course create your own sounds too. Avoid popular, published music in your game. Your game should not play classics by The Weeknd, Drake and friends, nor the latest hit from Ariana Grande or Billie Eilish. Dynamic instrumentals usually work best for backgrounds. But you may want to set a darker ambiance with slower music. Keep in mind that music and sounds establish a mood, and they are part of the design of your product.
Prepare sound files
Sometimes, you need to edit the sound files you download from the internet. Make sure to remove any silence at the start or end of the clip. Also, check the volume and the length of the clip. If you want it to loop, you may need to edit it as well. I won’t discuss how to do all this here.
Load the sounds in HTML
You will need to load your sound clips in the HTML file of your game. Sounds are assets, like images. I’ll explain below how to do this.
Setup the sounds in JS
Once you have the code in the HTML to load the sound files, you will need to set them up in the JS. This is very similar to the way we have handled images in this game.
Note that background music and sound effects will be treated a bit differently. You’ll see.
Trigger the sounds
When you want the sound to play in your game, you will need to call a trigger to play it. So you need to know when the sound must play: when you hit a baddy, when the game ends, when the player moves to a certain area of the canvas, etc.