We have a keyboard but there's no sound yet. Let's head back over to our JavaScript and load all of the audio files. We will create a new method called loadAudio()
and call it from the application's start()
method.
There are two ways by which we could load all the files. We could load them one at a time by calling audioManager.getAudio()
for each file, which would be very verbose and require a lot of typing. Or we can iterate over all of the piano-key
elements and get the filename from their data-note
attributes. By using this method we could add more piano keys to the HTML and wouldn't even have to touch the JavaScript:
function loadAudio() { var count = 0, loaded = 0, error = false; $(".keyboard .piano-key").each(function() { count++; var noteName = escape($(this).data("note")); audioManager.getAudio(noteName, function() { if (error) return; if (++loaded == count) setStatus("Ready."); else setStatus("Loading " + Math.floor(100 * loaded / count) + "%"); }, function(audio) { error = true; setStatus("Error loading: " + audio.src); } ); }); }
The first thing we do is define some variables to keep track of the number of audio files that are being loaded and the number that have been loaded. We will use those to calculate the percent complete. We also need a variable to set if we get an error loading a file.
The next thing we do is select all of the piano-key
elements using jQuery and call each()
to iterate over them. For each one we do the following:
count
variable to keep track of the total number of files.data-note
attribute. Notice that we must use the escape()
function because some notes contain the sharp sign #
, which is illegal in a URL.audioManager.getAudio()
passing in the note name. This will cause the audio file to get loaded and cached. The next time we call getAudio()
for this note, it will be loaded and ready to play.getAudio()
is a function that gets called when each file has finished loading successfully. In this function we increment the loaded variable. Then we check if all of the files have been loaded and if so, show a ready message. Otherwise, we compute the percent complete of loaded files and show it in the footer by calling setStatus()
.getAudio()
is a function that gets called if there is an error loading a file. When that happens, we set the error
variable to true
and display a message showing the file that couldn't be loaded.3.149.214.32