Example: Using All Three Formats
In Example 7-2, we are going to
embed a 40-second song, song1, in
an HTML5 page and play it. To make sure song1 can play in as many browsers as
possible, we are going to embed it with three different sources. For
this example, we are also going to set the autoplay
, loop
, and controls
properties so that the song will start automatically, replay when it
reaches the end, and display the default browser audio controls. Here is
the code to embed song1:
<audio
controls
autoplay
loop
>
<source
src=
"song1.mp3"
type=
"audio/mp3"
>
<source
src=
"song1.wav"
type=
"audio/wav"
>
<source
src=
"song1.ogg"
type=
"audio/ogg"
>
</audio>
Note
Just as we did with video, we have placed the audio type with the broadest support for iOS devices first in the list. This is because handheld devices do not do well with multiple embedded sources.
We created .ogg, .wav, and .mp3 versions of the song using Audacity. Example 7-2 gives the full code.
Example 7-2. Basic HTML5 audio revisited
<!doctype html>
<html
lang=
"en"
>
<head>
<meta
charset=
"UTF-8"
>
<title>
CH7EX2: Basic HTML5 Audio Revisited</title>
</head>
<body>
<div>
<audio
controls
autoplay
loop
>
<source
src=
"song1.mp3"
type=
"audio/mp3"
>
<source
src=
"song1.ogg"
type=
"audio/ogg"
>
<source
src=
"song1.wav"
type=
"audio/wav"
>
Your browser does not support the audio element.</audio>
</div>
</body>
</html>
Note
song1 was created 10 years ago using Sonic Foundry’s Acid music-looping software. Acid is an amazing tool for creating soundtracks because ...
Get HTML5 Canvas, 2nd Edition 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.