40
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 supportedAu
dioFormat() 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 audio file to load. We already introduced you to the canPlayType()
method in Chapter 6, but to refresh your memory, canPlayType() takes a single pa‐
rameter—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 that 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 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 supportedAudioFormat(audio) {
var returnExtension = "";
if (audio.canPlayType("audio/ogg") =="probably" ||
audio.canPlayType("audio/ogg") == "maybe") {
returnExtension = "ogg"; }
else if(audio.canPlayType("audio/wav") =="probably" ||
audio.canPlayType("audio/wav") == "maybe") {
returnExtension = "wav";
} else if(audio.canPlayType("audio/mp3") == "probably" ||
audio.canPlayType("audio/mp3") == "maybe") {
Playing a Sound with No Audio Tag | 393