Working with the Audio Tag

As mentioned, HTML5 defines an <audio> tag as part of the core HTML5 specification. It’s designed primarily for in-page sound playback, but the flexibility of the tag means that game developers have repurposed it for game audio as well.

Using the Audio Tag for Basic Playback

The <audio> tag can be used to create an on-page audio player with a single tag:

<audio src="music.mp3" controls/>

More interesting from a game development perspective, however, is that the <audio> tag can also be created entirely separate from a visual component using the Audio object as you saw briefly in Chapter 10, “Bootstrapping the Quintus Engine: Part II.”

var snd = new Audio();
snd.src = "music.mp3";
snd.addEventListener("canplaythrough",function() {
  snd.play();
});
snd.load();

The preceding example creates a new audio object, sets the source to the file music.mp3, and then starts the music playing as soon as the canplaythrough event triggers. canplaythrough means that the audio file has loaded enough that it can start playing, and if it keeps loading at the current rate, it will finish loading before the playback reaches the end of the file.

Dealing with Different Supported Formats

Also as mentioned in Chapter 10, different browsers support different audio formats, with no single format supported by all browsers currently. To cover the widest range of browsers, you need to support at least two formats: either .mp3 and .ogg or .mp3 and .wav. Because .ogg is lossy compressed ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.