HTML5 and CSS3, Second Edition

(singke) #1

Tip 20


Tip 20. Working with Audio


AwesomeCo is developing a site to showcase royalty-free audio loops for use
in screencasts, and it would like to see a mockup page of a single loop collec-
tion. When we’re done, we’ll have a list of the audio loops and a visitor will
be able to quickly audition each one. We don’t have to worry about finding
audio loops for this project, because the client’s sound engineer has already
provided us with the samples we’ll need in both MP3 and OGG formats. You
can find a small bit of information on how to encode your own audio files in
Appendix 3, Encoding Audio and Video for the Web, on page 273.

Building the Basic List


The audio engineer has provided us with four samples: drums, organ, bass, and
guitar. We need to describe each one of these samples using HTML markup.
Here’s the markup for the drums loop:

html5_audio/audio.html
<articleclass="sample">
<header><h2>Drums</h2></header>
<audioid="drums"controls>
<sourcesrc="sounds/ogg/drums.ogg"type="audio/ogg">
<sourcesrc="sounds/mp3/drums.mp3"type="audio/mpeg">
<ahref="sounds/mp3/drums.mp3">Downloaddrums.mp3</a>
</audio>
</article>

We define the <audio> tag first and tell it that we want to have some controls
displayed. Within the <audio> tag, we define multiple <source> tags, one for the
MP3 version and another for the OGG versions. The type attribute describes
the type of audio, and if we supply it, the browser doesn’t need to go to the
server to ask what format the video is; it can look at its supported types and
check very quickly. If it can’t play the first file it finds, it’ll try the next, until
there are no more <source> tags to try.

Finally, we display a link to allow the visitor to download the MP3 file directly.
This will show up if the browser doesn’t support the <audio> tag.

This basic bit of code will work in Chrome, Safari, and Firefox. Let’s put it
inside an HTML5 template with the three other sound samples.

report erratum • discuss

Working with Audio • 137


Download from Wow! eBook <www.wowebook.com>

Free download pdf