Game Development Reference
In-Depth Information
Adding the above snippet to a page will not result in anything visible. In order to add
more control to the tag, including adding a player to the page so that the user can
interact with it, we can choose from the elements associated with the tag. These at-
tributes are as follows:
autoplay : It starts playing the file right away as soon as the browser has
downloaded it
controls : It displays a visual player with buttons through which the user
can control audio playback
loop : It is used to continuously play the file indefinitely
muted : It is used when audio output is muted
preload : It specifies how the audio resource is to be preloaded by the
browser
To achieve a similar result through JavaScript, we can create a DOM element of type
audio, or instantiate a JavaScript object of type Audio. Adding the optional attributes
can be done the same way we would to any other JavaScript object. Note that creat-
ing an instance of Audio has the exact same effect as creating a reference to a DOM
element:
// Creating an audio file from a DOM element
var soundOne = document.createElement("audio");
soundOne.setAttribute("controls", "controls");
soundOneSource =
document.createElement("source");
soundOneSource.setAttribute("src",
"sound-file.mp3");
soundOneSource.setAttribute("type", "audio/
mpeg");
soundOne.appendChild(soundOneSource);
document.body.appendChild(soundOne);
// Creating an audio file from Audio
var soundTwo = new Audio("sound-file.mp3");
soundTwo.setAttribute("controls", "controls");
Search WWH ::




Custom Search