Loading audio files

You could define all of the audio files for your application by adding <audio> elements for each one to your HTML file. However, we can also load audio files dynamically from JavaScript to control how and when they are loaded. We can load them just like we loaded image files dynamically in the previous chapter. First, we create a new <audio> element and set the src attribute to the name of the audio file:

var audio = $("<audio>")[0];
audio.src = "2C.mp3";

Next, we add an event handler to get notified when the audio file has finished loading. There are two events that we can use. The canplay event is fired as soon as the browser has enough data to start playing the audio. The canplaythrough event is fired after the file has been ...

Get HTML5 Web Application Development By Example Beginner's guide 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.