HTML and CSS Reference
In-Depth Information
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 embedded in an
HTML page and as instances of
HTMLAudioElement
when created dynamically in JavaScript.
However, they are essentially the same.
NOTE
Don'tfretifyoudon'tlikeusingglobalvariables.Bytheendofthischapter,wewillshowyouaway
to make these variables local to your canvas application.
Next, we create our event handler for the window
load
event named
eventWindowLoaded()
.
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
au-
dio
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
false
);
var
var
audioElement
;
function
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 val-
id 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 cre-
ate 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 exten-
sion, we concatenate it with the name of the sound we want to load, and we set the
src
with a
call to the
setAttribute()
method of the
HTMLAudioElement
object:
var
var
audioType
=
supportedAudioFormat
(
audioElement
);
If a valid extension from
supportedAudioFormat()
is not returned, something has gone
wrong and we need to halt execution. To handle this condition in a simple way, we create