HTML5 and CSS3, Second Edition

(singke) #1
Fallbacks with audio are relatively easy, and some of your users may appre-
ciate the ability to easily download the file, so you might consider not hiding
the links at all.

If you want to do something more advanced, you need to detect support for
audio. You can do basic detection by creating a new audio element in JavaScript
and checking whether it responds to the canPlayType() method, like this:

varcanPlayAudioFiles= !!(document.createElement('audio').canPlayType);

If you want to detect support for a certain type of audio file, you’d then use
the canPlayType() method on the audio element:

varaudio= document.createElement('audio');
if(audio.canPlayType('audio/ogg')){
// playsogg files
}

The canPlayType() method doesn’t return Boolean values. Instead of true or false
values, you’ll get one of the following string values back:


  • "probably", meaning it’ll most likely work.

  • "maybe", meaning it might work.

  • "", an empty string, which is considered “falsey.” That means that although
    it’s not a Boolean false, JavaScript won’t see it as true.


Modernizr has a little better support for checking audio availability. It wraps
canPlayType(), creating some nice convenience methods:

if(Modernizr.audio.ogg){
// playsogg files
}

if(Modernizr.audio.mp3){
// playsMP3 files
}

However, Modernizr still uses the HTML5 specification’s return values for
testing audio formats playable by a browser.

Playing audio in the browser natively is just the beginning. Browsers are
starting to support the HTML5 JavaScript application programming interfaces
(APIs) for audio and video, which you can read about in Explore the Media
Content JavaScript API, on page 149.

Now that you know how to make audio work natively, let’s look at how we do
the same with video.

Chapter 7. Embedding Audio and Video • 140


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf