Lesson 2: Playing audio CHAPTER 11 445
In this example, the <audio> element is configured with the controls attribute, which pro-
vides controls to start and stop the audio, to view and set the audio cursor location, and to
set the volume. The <audio> element contains a <source> element that describes the audio
source as .mp3. The <audio> element also contains text that is displayed on browsers that
don’t support the <audio> element.
One characteristic of audio is that the developer might play multiple audio files at the
same time. Although this is common in games, most browsers can’t handle playing multiple
audio files at the same time.
Setting the source
The <source> element specifies an audio source. At a minimum, you need to set the src
attribute to the URL of the audio. You should also include more than one <source> element
to provide many sources so the browser can choose the most appropriate audio codec. In the
following example, the same sound has been rendered for each of the three most popular
formats.
<audio id="audio" controls="controls">
<source src="media/kittycat.oga" type='audio/ogg; codecs="vorbis"' />
<source src="media/kittycat.wav" type='audio/wav; codecs="1"' />
<source src="media/kittycat.mp3" type='audio/mpeg; codecs="mp3"' />
</audio>
By providing multiple formats, the browser can choose the format that displays the audio,
which provides the most compatible experience to users. As mentioned earlier, the position
of the <source> elements is important because a browser starts looking at the top and stops
when it finds a file it can display. The recommended order is to start with the .oga file because
it’s royalty free, open source, and becoming more popular for the web. Next, use the .wav file,
because it is also quite popular. Finally, use the .mp3 for browsers that don’t support .oga and
.wav files.
The type attribute includes both the MIME type and the codecs. Although the type
attribute isn’t usually required, the browser can use it to help choose the proper audio file to
display.
Configuring the
The <audio> element can be configured to provide the behavior you need for your webpage.
The following is the list of attributes you can use to configure the <audio> element to suit
your needs.
■■autoplay pecifies that audio starts playing immediately.S
■■controls pecifies that the play/pause button, audio cursor, and maximize are S
displayed.
■■loop pecifies that the audio repeats when it has reached the end of its stream.S