HTML5 Canvas [122]
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 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"; } 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") {
returnExtension = "mp3";
}
return returnExtension;
}
Notice that we do not check for a condition when no valid audio format is found and the return value is “”. If that is the case, the code that has called this function might need to be written in a way to catch that condition and alter the program execution. We did that with the test of the return value and the alert() message, which we described in the previous section.
NOTE
If you want to test the error condition with no valid return value from this function, simply add an extra character to the MIME type (e.g., audio/oggx) to make sure an empty string is always returned.
Alternatively, you can use Modernizr to test for audio support. If you have included the Modernizr JavaScript library in your HTML page (as we have done in every application we have written thus far), you can access the static values of Modernizr.audio.ogg, Modernizr.audio.wav, and Modernizr.audio.mp3 to test to see whether those types are valid. These are not Booleans—they evaluate to the same probably, maybe, and “” values that we get from a call to canPlayType(). If you are comfortable using Modernizr for all your tests, you can replace the test in the code with tests of these Modernizr static values.
Playing the Sound
Finally, we get to the point where we can play a sound inside our canvasApp() function. Since we preloaded the sound originally outside the context of this function into a variable with a global scope, we just need to call the play() function audioElement to start playing the sound:
audioElement.play();
Figure 7-4 shows what this canvas application will look like when executed in an HTML5-compliant web browser (notice that we have left the display of the audio properties in this application).
Figure 7-4. Sound loaded and played “on” the canvas
Look Ma, No Tag!
Now, check out the full application in Example 7-4. Notice that there is no