HTML and CSS Reference
In-Depth Information
THE BASICS OF AUDIO IN HTML5
One of the most exciting new tags in the HTML5 collection is
<audio>
. With it you can play
audio i les using the speakers on your computer or headset on a mobile device. h e basic
format to select a sound i le to play is:
<
audio src
=
”jazz.mp3”
></
audio
>
h e
src
attribute works just like it does in an
<img>
tag — it's a reference to the source of
the i le. However, to get the audio to play, you need to look at the attributes.
AUTOPLAY
h e
autoplay
attribute is fairly self-explanatory. As soon as the page loads, the sounds begin
to play. Before adding the
autoplay
attribute, you want to be sure that all your users are
going to be okay with listening to whatever you're playing. One way to guarantee that users
will not return to a page is to have a continuous sound that automatically turns on. h at
concern aside, the following script (
BasicAudio.html
in this chapter's folder at
www.
wiley.com/go/smashinghtml5
) shows how to create a simple page that begins playing
as soon as it's launched:
<!
DOCTYPE HTML
>
<
html
>
<
head
>
<
meta http
-
equiv
=
”Content-Type”
content
=
”text/html; charset=UTF-8”
>
<
title
>
Basic Audio
</
title
>
</
head
>
<
body
>
Audio is between the lines
<
br
>
----------------------------------------
<
br
>
<
audio src
=
”jazz.wav”
autoplay
></
audio
>
<
br
>
----------------------------------------
</
body
>
</
html
>
200
You can test that script with any browser except Google Chrome because it's the only one that
doesn't recognize sound i les in the
.wav
format. Use an
.mp3
or
.ogg
sound i le instead for
Chrome testing.
CONTROLS
As noted, if your sound (music, sound ef ects, or even just talking) annoys your users, they're
not going to return. So, how do you control sound? h e easiest way is to add the
controls
attribute. As with
autoplay
, you don't have to give it a value. Just include it within the
<audio>
tag, and it automatically appears. Try the following program (
Controls.html
in this chapter's folder at
www.wiley.com/go/smashinghtml5
):