Monday, December 6, 2010

Creating an advanced preloader using AS3

Today we'll make an advanced preloader, which shows the total size of the file, how many kbs are downloaded, percentage, download speed and estimated remaining time.

Check it out:


Here is the full code. There's one textfield on the stage called load_text, all the data is displayed there. When I needed to start a new line, I used "\n".

import flash.utils.Timer;

stop();

var totalB:Number = 0;
var loadedB:Number = 0;
var speed:Number = 0;
var previousB:Number = 0;
var eta:Number = 0;
var speedTimer:Timer = new Timer(1000);
speedTimer.start();
speedTimer.addEventListener(TimerEvent.TIMER, speedManager);

function speedManager(TimerEvent):void
{
speed = loadedB - previousB;
previousB = loadedB;
}

stage.addEventListener(Event.ENTER_FRAME, loadManager);

function loadManager(Event):void
{
totalB = this.stage.loaderInfo.bytesTotal;
loadedB = this.stage.loaderInfo.bytesLoaded;

if (speed == 0)
{
eta = 0;
}
else
{
eta = Math.round((totalB-loadedB)/speed);
}

load_text.text = "Loaded: " + Math.round(loadedB/1024)
+ " kb\n out of " + Math.round(totalB/1024) + " kb\n\n"
+ Math.floor((loadedB/totalB)*100) + "%\n\n"
+ "Speed: " + Math.round(speed/1024) + " kb/s\n"
+ "ETA: " + eta + " sec";
}

As you can see, I only needed to get 2 pieces of data - bytesTotal and bytesLoaded, everything else is calculated with code. A timer is there to capture the download speed. When managing "eta" variable, I need to first check whether speed equals 0, because if it does, then I can't divide by zero, so I just set eta to 0. Everything else is pretty self-explanatory.

Thanks for reading!

3 comments:

Anonymous said...

This is the worst tutorials I've ever seen, the piece of code above does not make any sense, where is the loader?

Kirill Poletaev said...

Do you see the "advanced" word in the title? It basically means that this tutorial is meant for people that have some basic understanding in AS3 and how preloaders work. That clearly isn't you. I suggest you do some basic research on programming and see how basic preloaders work before moving on to advanced techniques.

dontworryaboutitmate said...

Huh, I don't understand the hateful comments?
The loader is advanced in comparison to just a loading bar and it's playing at the top of the page...

Post a Comment