I'm making my first javascript game (Snake), and I've already finished most of it. Now I'm trying to add sound, but it's not working. I'm not using a server, I'm using a local html file.
This is the constructor method of the class where I'm trying to play a sound:
constructor(){
...
this.collect_wav = new Audio("Sounds\\Coin.wav");
...
}
And later in one of the methods:
relocate(){
...
this.collect_wav.play();
}
When the code runs, the new Audio
runs without an error, but on the line play()
, I get this error in the developer console:
There is a "Sounds" folder in the same directory as my html file, and inside that folder is
Coin.wav
, so I think the path is correct, but it just doesn't work. But when I go into the developer console, and go to the sources
tab, I don't even see the Sounds
folder listed, only the html, css, and javascript files are there:
I have tried using the html tag like this:
<audio controls>
<source src="Sounds/Coin.wav" type="audio/wav">
</audio>
Even this doesn't work, I see the controls show up, but it is greyed out and cannot be interacted with:
I have also tried replacing the backslashes with a normal slash (Because I'm not sure which one is correct in html), but this also didn't help. I have been trying to fix this for days, and I really have no idea what's wrong.
Years later, I've finally discovered the reason I encountered this problem. It has nothing to do with Javascript or whether the HTML file containing the audio was loaded from a local file or a server.
Apparently Chrome (and probably all Chromium-based web browsers as well) cannot play audio files with a bitrate less than 100 kb/s (according to this SO answer), and the audio file I tried to play had a bitrate of 88 kb/s. Therefore it refused to play even if I directly loaded it in Chrome by typing the file URI that points to it (i.e. file:///path/to/Coin.wav
).
After using audio editing software to re-encode that audio file to have a bitrate greater than 100 kb/s, it now plays correctly.