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"/>

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:;

To pause the track:


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

lAudioNote.volume = 0.7;