HTML and CSS Reference
In-Depth Information
Finding the Supported Audio Format
Before the code in the previous section will work, we need to define the
supportedAudi-
oFormat()
function. Because we are adding
audio
objects dynamically to the HTML page,
we do not have a way to define multiple
<source>
tags like we can in HTML. Instead, we
are going to use the
canPlayType()
method of the
audio
object to tell us which type of au-
to refresh your memory,
canPlayType()
takes a single parameter—a MIME type. It returns
a text string of
maybe
,
probably
, or
""
(nothing). We are going to use these values to figure
we are going to assume that both
maybe
and
probably
equate to
yes
. If we encounter either
result with any of our three MIME types (
audio/ogg
,
audio/wav
,
audio/mp3
), we will return
the extension associated with that MIME type so that the sound file can be loaded.
NOTE
The next function is essentially the same as the one we created in
Chapter 6
to handle video formats.
The obvious changes here are with the MIME types for audio.
In the following function,
audio
represents the instance of
HTMLAudioElement
that we will
test. The
returnExtension
variable represents that valid extension for the first MIME type
found that has the value of
maybe
or
probably
returned:
function
function
supportedAudioFormat
(
audio
) {
var
var
returnExtension
=
""
;
iif
(
audio
.
canPlayType
(
"audio/ogg"
)
==
"probably"
||
audio
.
canPlayType
(
"audio/ogg"
)
==
"maybe"
) {
returnExtension
=
"ogg"
;
}
else
else iif
(
audio
.
canPlayType
(
"audio/wav"
)
==
"probably"
||
audio
.
canPlayType
(
"audio/wav"
)
==
"maybe"
) {
returnExtension
=
"wav"
;
}
else
else iif
(
audio
.
canPlayType
(
"audio/mp3"
)
==
"probably"
||
audio
.
canPlayType
(
"audio/mp3"
)
==
"maybe"
) {
returnExtension
=
"mp3"
;
}
return
return
returnExtension
;
}