HTML and CSS Reference
In-Depth Information
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 comparable to .mp3's small
file size, it's a better choice than .wav.
If you want to support this from a markup perspective, you can use separate source tags and count on
browsers to pick the first one that they support:
<audio controls>
<source src="music.mp3" type="audio/mp3" />
<source src="music.ogg" type="audio/ogg" />
</audio>
If you use JavaScript to load the file, you can use the canPlayType method on the Audio object to check
for support to decide which element to load:
var snd = new Audio();
if(snd.canPlayType('audio/mpeg')) {
snd.src = "music.mp3";
} else if(snd.canPlayType('audio/ogg; codecs="vorbis"') {
snd.src = "music.ogg";
}
// ... load and play the sound
Because the audio/ogg mime type is a container that can support multiple different codecs, you need to
check for the specific code (generally “vorbis” for audio) to use.
Search WWH ::




Custom Search