Controlling HTML5 Audio from JavaScript

February 20, 2011

This post covers some code for manipulating a HTML 5 audio tag using javascript.

Here's an example audio tag in HTML5:

<audio id="audio1">
  <source src="/site_media/sounds/audio.ogg" type="audio/ogg"/>
  <source src="/site_media/sounds/audio.wav" type="audio/wave"/>
  <source src="/site_media/sounds/audio.mp3" type="audio/mp3"/>
</audio>

We specify the three different formats so we support all the different browsers.

To get hold of this audio element using JavaScript:

var lAudioNote = document.getElementById("audio1");

To play the track:

lAudioNote.play();

To pause the track:

lAudioNote.pause();

To set the volume (scale is 0 to 1):

lAudioNote.volume = 0.7;

References