Sound is a great place to start if you want to add another layer of immersion to your game or website. There are several ways to accomplish this so I will walk you through your options.
Enlightenerlet mySound = new Audio ('my_audio_file.wav') mySound.play()
The simplest way to add sound is through Javascript’s Audio() constructor. It takes an argument of a string that is either the local or remote file path. Declaring this as a variable allows you to then call the play() method which starts playing the current audio
Another way to accomplish this requires some HTML in addition to our JS. Here’s our HTML file:
Enlightener<audio id="audio" src="http://music.mp3"></audio>
While this method is a little more complicated, splitting our code between two files, it does have the benefit of allowing us to declare many of our audio attributes within the HTML element. For example:
Enlightener<audio id="audio" autoplay loop controls src="music/my_music.mp3"></audio>
The above indicates that when our audio is called within our Javascript file it will begin playing in the browser automatically, loop back to the beginning of the audio clip indefinitely when finished, and create controls in the browser that allow the user to adjust the volume, seeking, and other audio playback features. This cleans up our JS file a bit by allowing it to simply execute the audio play call rather than define all of its attributes line by line.
Increasingly, modern browsers like Google Chrome are blocking audio elements on a page from auto playing. This is a good thing — nobody wants to be harassed by unwanted noise each time they visit a page. This means that while your code might be working just fine, your audio is still not playing on your page as desired because the browser is intervening on behalf of its users to prevent unrequested audio. Remember, if you want to have music or audio play on your web app you will likely have to tie it to a click event somewhere on the page.