Look Ma, No Tag!
Now check out the full application in Example 7-4. Notice that there is no
<audio>
tag defined in the
HTML, but the sound still plays. This is our first step toward
integrating HTMLAudioElement
objects
with HTML5 Canvas.
Example 7-4. Playing a sound with no tag
<!doctype html>
<html
lang=
"en"
>
<head>
<meta
charset=
"UTF-8"
>
<title>
CH7EX4: Playing A Sound With No Tag</title>
<
script
src
=
"modernizr.js"
><
/script>
<
script
type
=
"text/javascript"
>
window
.
addEventListener
(
'load'
,
eventWindowLoaded
,
false
);
var
audioElement
;
function
eventWindowLoaded
()
{
audioElement
=
document
.
createElement
(
"audio"
);
document
.
body
.
appendChild
(
audioElement
);
var
audioType
=
supportedAudioFormat
(
audioElement
);
if
(
audioType
==
""
)
{
alert
(
"no audio support"
);
return
;
}
audioElement
.
addEventListener
(
"canplaythrough"
,
audioLoaded
,
false
);
audioElement
.
setAttribute
(
"src"
,
"song1."
+
audioType
);
}
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
;
}
function
canvasSupport
()
{
return
Modernizr
.
canvas
;
}
function
audioLoaded
(
event
)
{
canvasApp
();
}
function
canvasApp
()
{
if
(
!
canvasSupport ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.