HTML and CSS Reference
In-Depth Information
Instead of calling the play() function of each sound directly, we are going to create a
function named playSound() . This function accepts two parameters:
One of the constants 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
The function here creates a new sound object every time it is called by calling the
createElement() function of the document DOM object. It then sets the properties
( 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;
tempSound.volume = volume;;
To play the sounds, we call playSound() , passing the proper parameters.
The call in eventMouseUp() looks like this:
And in drawScreen() it looks like this:
To display on the canvas how many sounds we have created, we add this code to the
drawScreen() function:
context.fillStyle = "#FFFFFF";
context.fillText ("Active Sounds: " + sounds.length, 200 ,480);
Now, go ahead and try this example ( CH7EX7.html in the code distribution). Fig-
ure 7-8 shows what Space Raiders iteration #2 looks like. Notice we have added some
display text at the bottom of the screen to show how many sounds are in the sounds
array. You will discover two issues with this iteration:
1. The sounds play with almost no pauses when loaded from a local drive. But when
the page is loaded from a remote website, there is a defined pause before each sound
is loaded and played.
2. The number of sound objects created is a huge problem. For some browsers, such
as Chrome, the number of active sounds caps out at about 50. After that, no sounds
play at all.
Search WWH ::

Custom Search