I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
It's easy, just get your audio
element and call the play()
method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load()
, pause()
, and a few other properties of the audio
element.
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
repeat as needed for all audio in the game
Then:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
repeat as needed except do not pause the audio you want to hear when the game starts
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
new Audio('./file.mp3').play()
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();