Sound
files can be large and take a long time to load, especially if they
are loaded from the Internet. An application can play sounds before
they are fully loaded. You might want to give the user an indication
of how much of the sound data has been loaded and how much of the
sound has already been played.
The Sound class dispatches two events that make it relatively
easy to display the loading progress of a sound:
progress
and
complete
.
The following example shows how to use these events to display progress
information about the sound being loaded:
var s = new Sound();
s.addEventListener(air.ProgressEvent.PROGRESS,
onLoadProgress);
s.addEventListener(air.Event.COMPLETE,
onLoadComplete);
s.addEventListener(air.IOErrorEvent.IO_ERROR,
onIOError);
var req = new air.URLRequest("bigSound.mp3");
s.load(req);
function onLoadProgress(event)
{
var loadedPct = Math.round(100 * (event.bytesLoaded / event.bytesTotal));
air.trace("The sound is " + loadedPct + "% loaded.");
}
function onLoadComplete(event)
{
var localSound = event.target;
localSound.play();
}
function onIOError(event)
{
air.trace("The sound could not be loaded: " + event.text);
}
This code first creates a Sound
object and then adds listeners to that object for the
progress
and
complete
events.
After the
Sound.load()
method has been called and
the first data is received from the sound file, a
progress
event occurs,
and triggers the
onSoundLoadProgress()
method.
The fraction of the sound data that has been loaded is equal
to the value of the
bytesLoaded
property of the
ProgressEvent object divided by the value of the
bytesTotal
property.
The same
bytesLoaded
and
bytesTotal
properties
are available on the Sound object as well.
This example also shows how an application can recognize and
respond to an error when loading sound files. For example, if a
sound file with the given filename cannot be located, the Sound
object dispatches an
ioError
event. In the previous
code, the
onIOError()
method executes and displays
a brief error message when an error occurs.