HTML and CSS Reference
In-Depth Information
Playing a Sound with No Audio Tag
Now that we have a sound playing in an HTML5 page and we are tracking the properties
of the
audio
element on the canvas, it is time to step up their integration. The next step
is to do away with the
<audio>
tag embedded in the HTML page.
If you recall from
Chapter 6
, we created a
video
element dynamically in the HTML
page and then used the
canPlayType()
method of the
HTMLVideoElement
object to figure
out what video file type to load for a particular browser. We will do something very
similar for audio.
Dynamically Creating an Audio Element in JavaScript
The first step to dynamically creating
audio
elements is to create a global variable named
audioElement
. This variable will hold an instance of
HTMLAudioElement
that we will use
in our canvas application. Recall that
audio
elements in an HTML page are instances
of the
HTMLAudioElement
DOM object. We refer to them as
audio
objects when embed-
ded in an HTML page, and as instances of
HTMLAudioElement
when created dynamically
in JavaScript. However, they are essentially the same.
Don't fret if you don't like using global variables. By the end of this
chapter, we will show you a way to make these variables local to your
canvas application.
Next, we create our event handler for the window
load
event named
eventWindow
Loaded()
. Inside that function, we call the
createElement()
function of the DOM
document
object, passing the value
audio
as the type of element to create. This will
dynamically create an
audio
object and put it into the DOM. By placing that object in
the
audioElement
variable, we can then dynamically place it onto the HTML page with
a call to the
appendChild()
method of the
document.body
DOM object:
window.addEventListener('load', eventWindowLoaded, false);
var audioElement;
function eventWindowLoaded() {
audioElement = document.createElement("audio");
document.body.appendChild(audioElement);
However, just having a dynamically created
audio
element is not enough. We also need
to set the
src
attribute of the
HTMLAudioElement
object represented by
audioElement
to
a valid audio file to load and play. But the problem is that we don't yet know what type
of audio file the current browser supports. We will get that information from a function
we will create named
supportedAudioFormat()
. We will define this function so that it
returns a string value representing the extension of the file type we want to load. When
we have that extension, we concatenate it with the name of the sound we want to load,
and set the
src
with a call to the
setAttribute()
method of the
HTMLAudioElement
object: