Time for action – creating an AudioManager object
Let's encapsulate the loading of audio files into a re-usable object. We will create a new object called AudioManager
and place it in a file named audioManager.js
. This object will abstract all of the code needed to load, cache, and access audio files.
The constructor for our object takes one parameter named audioPath
, which is the path to where audio files are stored:
function AudioManager(audioPath) { audioPath = audioPath || ""; var audios = {}, audioExt = getSupportedFileTypeExt();
If audioPath
isn't defined, we default it to an empty string. Then we add a variable named audios
which is an object that will be used to cache all of the <audio>
elements that are loaded. Finally, we define a variable to hold the audio file extension supported by the browser, which we will determine by calling the getSupportedFileTypeExt()
method:
function getSupportedFileTypeExt() { var audio = $("<audio>")[0]; ...