HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to play audio?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
audiohowplay

Problem

I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

Solution

If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();




function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}

Play Audio



This uses the HTMLAudioElement interface, which plays audio the same way as the ` element.

If you need more functionality, I used the howler.js library and found it simple and useful.





var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
`

Context

Stack Overflow Q#9419263, score: 2007

Revisions (0)

No revisions yet.