HTML5 LogoScripting Sound in HTML5

Back back to the main Sound page

Using JavaScript

Using JavaScript provides a range of useful techniques for the creative use of sound in a web site. The examples on this page assume that you've worked through the JavaScript tutorials, in particular the material about events and functions in the button example.

As an example, here is an image and, when you roll the mouse over the image, it will start a sound playing, and when you take the mouse out, it will stop:

Novation Nova

We will see that this is done using the onmouseover and onmouseout events to invoke JavaScript functions. However, the first thing to note is that the page contains an audio element, which has the following definition:

<audio id="synth">
  <source src="ddppl-excert.ogg" type="audio/ogg">
  <source src="ddppl-excert.mp3" type="audio/mpeg">
</audio>

You can find a brief description of the HTML5 audio tag here. In this case we are giving the element an ID so we can refer to it later. Because we are not specifying a control attribute, the element is hidden, and not displayed in the page. Look at the source for this page and find this element.

The HTML for the image is:

<img src="Nova.png" alt="Novation Nova" width="200" height="65"
     onmouseover="playSound('synth');"
     onmouseout="stopSound('synth');"
/>

where you can see the handlers for the mouse events. The function which is called to start the sound has the following definition:

function playSound(elementId)
{
  var el = document.getElementById(elementId);
  if (el != null) {
    el.currentTime = 0;
    el.play();
  }
}

That function is given the ID of the audio element as a parameter which is used to get the element from the document. If the element can be found then, first, the current time is set to 0 to ensure that the sound always starts from the beginning, then the play method is called to start the sound playing.

In contrast, the function to stop the sound has the following definition:

function stopSound(elementId)
{
  var el = document.getElementById(elementId);
  if (el != null) {
    el.pause();
  }
}

This function finds the audio element and calls the pause method. This stops the sound from playing.

You will also notice there is a sound attached to the onmouseover event of the back button at the top of this page. This uses the same playSound function as discussed above. However, instead of specifying the synth audio element, it specifies the file pageturn elemen - find the source in the page to confirm this for yourself.

Notice that, in contrast to the pre-HTML5 technique, we do not need to rewrite any of the page content. This is more efficient as the browser does not then need to reparse any of the content.