Preloading MP3 files

When you preload MP3 files, you can use the setInterval() function to create a polling mechanism that checks the bytes loaded for a Sound or NetStream object at predetermined intervals. To track the downloading progress of MP3 files, use the Sound.getBytesLoaded() and Sound.getBytesTotal() methods.

The following example uses setInterval() to check the bytes loaded for a Sound object at predetermined intervals.

To preload an MP3 file:

  1. Create a new FLA file called preloadMP3.fla.
  2. Select Frame 1 on the Timeline and type the following code in the Actions panel:
    // Create a new Sound object to play the sound.
    var songTrack:Sound = new Sound();
    // Create the polling function that tracks download progress.
    // This is the function that is "polled." It checks 
    // the downloading progress of the Sound object passed as a reference.
    function checkProgress (soundObj:Object):Void {
        var numBytesLoaded:Number = soundObj.getBytesLoaded();
        var numBytesTotal:Number = soundObj.getBytesTotal();
        var numPercentLoaded:Number = Math.floor(numBytesLoaded / numBytesTotal * 100);
        if (!isNaN(numPercentLoaded)) {
            trace(numPercentLoaded + "% loaded.");
        }
    };
    // When the file has finished loading, clear the interval polling.
    songTrack.onLoad = function ():Void {
        trace("load complete");
        clearInterval(poll);
    };
    // Load streaming MP3 file and start calling checkProgress(),
    songTrack.loadSound("http://www.helpexamples.com/flash/sound/song1.mp3", true);
    var poll:Number = setInterval(checkProgress, 100, songTrack);
    
  3. Select Control > Test Movie to test the sound.

    The Output panel shows loading progress.

You can use the polling technique to preload external FLV files. To get the total bytes and current number of bytes loaded for an FLV file, use the NetStream.bytesLoaded and NetStream.bytesTotal properties (for more information, see bytesLoaded (NetStream.bytesLoaded property) and bytesTotal (NetStream.bytesTotal property)).

For more information, see MovieClip.getBytesLoaded(), MovieClip.getBytesTotal(), setInterval(), Sound.getBytesLoaded(), and Sound.getBytesTotal() in the ActionScript 2.0 Language Reference.

For information on creating a progress bar animation, see Creating a progress bar for loading MP3 files with ActionScript.

For a sample source file that loads MP3 files, jukebox.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the ComponentsAS2/Jukebox folder to access this sample. This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components.


Flash CS3


 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00001029.html