How to play audio?

Ryan S. picture Ryan S. · Feb 23, 2012 · Viewed 922.3k times · Source

I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

Answer

Uri picture Uri · Sep 5, 2013

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/examples/t-rex-roar.mp3');
  audio.play();
}
<button onclick="play()">Play Audio</button>

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


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

<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
    var sound = new Howl({
      src: ['https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3'],
      volume: 0.5,
      onend: function () {
        alert('Finished!');
      }
    });
    sound.play()
</script>