HTML and CSS Reference
In-Depth Information
var audioType = supportedAudioFormat(audioElement);
If a valid extension from supportedAudioFormat() is not returned, something has gone
wrong and we need to halt execution. To handle this condition in a simple way we
create an alert() message and then return from the function, effectively halting exe-
cution. While this is not a very robust form of error handling, it will work for the sake
of this example:
if (audioType == "") {
alert("no audio support");
return;
}
audioElement.setAttribute("src", "song1." + audioType);
Finally, like we did with video, we will listen for the canplaythrough event of audio
Element so that we know when the sound is ready to play:
audioElement.addEventListener("canplaythrough",audioLoaded,false);
Finding the Supported Audio Format
Before the code in the previous section will work, we need to define the supported
AudioFormat() function. Since 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 audio file to load. We already introduced you to the canPlayType()
method in Chapter 6 , but 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 out which media type to load and play. Just
like in Chapter 6 , and for the sake of this exercise, 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 the sound file can be loaded.
The next function is essentially the same as the one we created in Chap-
ter 6 to handle video formats. The obvious changes here are with the
MIME types for audio.
In the function below, 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 supportedAudioFormat(audio) {
var returnExtension = "";
if (audio.canPlayType("audio/ogg") =="probably" ||
audio.canPlayType("audio/ogg") == "maybe") {
returnExtension = "ogg";
Search WWH ::




Custom Search