HTML and CSS Reference
In-Depth Information
Iteration #2: Creating Unlimited Dynamic Sound Objects
So,we almost got what we wanted with the first iteration, but we ran into some oddities when
calling the play() function on a single HTMLAudioElement multiple times before the sound
had finished playing.
wesimplycreateanew HTMLAudioElement objecteverytimewewanttoplayasound.Ifthis
doesn't soundlike an efficient use ofmemory orresources in the web browser,youare a keen
observer. It's actually a horrible idea. However, let's proceed just to see what happens.
In canvasApp() , we will create a couple variables that represent the filenames of the sounds
we want to play, but without the associated extension. We will still retrieve the extension with
acallto supportedAudioFormat() ,justaswedidinthefirstiteration,andstorethatvaluein
the audioType variable.
Wewillalsocreateanarraynamed sounds thatwewillusetoholdallthe HTMLAudioElement
objects we create. This array will tell us how many objects we have created so that we can
visually see when all heck breaks loose:
var SOUND_EXPLODE = "explode1" ;
var SOUND_SHOOT = "shoot1" ;
var sounds = new
new Array ();
Insteadofcallingthe play() functionofeachsounddirectly,wearegoingtocreateafunction
named playSound() . This function accepts two parameters:
One of the variables we created above that contains the name of the sound file
A number between 0 and 1 that represents the volume of the sound to play
Thefunctionherecreatesanew sound objecteverytimeitiscalledbycallingthe createEle-
ment() functionofthe document DOMobject.Itthensetstheproperties( src , loop , volume )
and attempts to play the sound. Just for fun, let's push the object into the sounds array:
function playSound ( sound , volume ) {
var tempSound = document . createElement ( "audio" );
tempSound . setAttribute ( "src" , sound + "." + audioType );
tempSound . loop = false
false ;
tempSound . volume = volume ;
tempSound . play ();
Search WWH ::

Custom Search