HTML and CSS Reference
In-Depth Information
const MAX_SOUNDS = 8;
var soundPool = new Array();
The big change here is the playSound() function. It uses the same parameters as the one
from iteration #2, but the functionality is very different:
function playSound(sound,volume) {
The first half of the function loops through the soundPool array to see whether any of
the HTMLAudioElement objects in the pool are available to play a sound. We determine
this by checking the ended property. Since only HTMLAudioElement objects that have
previously been used to play a sound are put into the pool, the ended property will be
set to true once the sound has finished playing. By replaying sounds that have finished,
we remove the issue of trying to reuse an HTMLAudioElement object to play a sound while
it is already in use:
var soundFound = false;
var soundIndex = 0;
var tempSound;
if (soundPool.length> 0) {
while (!soundFound && soundIndex < soundPool.length) {
var tSound = soundPool[soundIndex];
if (tSound.ended) {
soundFound = true;
} else {
if (soundFound) {
tempSound = soundPool[soundIndex];
tempSound.setAttribute("src", sound + "." + audioType);
tempSound.loop = false;
tempSound.volume = volume;;
If we don't find a sound, and the size of the pool is less than MAX_SOUNDS , we go ahead
and create a new HTMLAudioElement , call its play() function, and push it into the sound
pool. This keeps the pool from getting too large, while making sure there are not too
many HTMLAudioElement objects in the browser at any one time:
} else if (soundPool.length < MAX_SOUNDS){
tempSound = document.createElement("audio");
tempSound.setAttribute("src", sound + "." + audioType);
tempSound.volume = volume;;
Search WWH ::

Custom Search