HTML and CSS Reference
In-Depth Information
take certain precautions. It's important to provide your audio samples in a range of formats so browsers
can pick the one they support.
In this example, We again go back to the 05-bouncing-2.html file from Chapter 6, with the ball that
bounces off walls. Each time the ball hits a wall, it should make a sound.
The first thing you need is a sound to play. You can download one from the Internet, use one of your own,
or use the audio clips that are provided with the rest of the example code. Place them in the same
directory as your document.
Now you need to include the following audio tag in the body of your HTML document:
<audio id="sound">
<source src="boing.ogg"/>
<source src="boing.mp3"/>
<p>This browser does not support the <code>audio</code> element.</p>
</audio>
Here we create an audio element and provide it with a pair of formats to pick from: Ogg Vorbis and MP3.
Between these two, you should have all the major browsers covered. We also provide a fallback message
to display in case the browser does not support the HTML5 audio element. This message is ignored if it
does.
We can access the audio element from JavaScript using the DOM interface and assign it to a variable:
var sound = document.getElementById('sound');
The sound should be ready, and all you have to do is call its play method:
sound.play();
In the next example, we use JavaScript to check if the browser supports the audio element before we start
the animation loop. If it's not supported, we display a blank canvas and throw an error message to the
browser's debugging console. To test for audio support, you can check whether the audio object that
returns from the DOM contains the canPlayType method:
if (typeof sound !== 'object' || !sound.canPlayType) {
throw new Error("The audio element is not supported in this browser.");
}
Here's the code for the example, 16-sound-events.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sound Events</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<audio id="sound">
<source src="boing.ogg" />
Search WWH ::




Custom Search