O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.8. Getting the Percentage of an Asset That Has Loaded

Problem

You want to determine what percentage of an asset has loaded.

Solution

Use the getBytesLoaded( ) and getBytesTotal( ) methods. Alternatively, you can create a custom percentLoaded property for the Sound and MovieClip classes.

Discussion

You can use the getBytesLoaded( ) and getBytesTotal( ) methods to determine the percentage of an asset that has loaded. The percentage is calculated by determining the ratio of the bytes loaded to the total bytes:

ratio = myObj.getBytesLoaded() / myObj.getBytesTotal(  );

The ratio is always between 0 and 1. Therefore, to format the percentage for display, you can multiply the ratio by 100. If you want the percentage to be a whole number, you can round the result as well:

percentLoaded = Math.round(ratio * 100);

The only caveat is that before any information about the asset has been retrieved (such as its file size), the getBytesLoaded( ) and getBytesTotal( ) methods both return 0, and 0 divided by 0 does not yield a valid number. Therefore, you should also use the isNaN( ) (is Not-a-Number) function to catch if the percentage is not a valid number and set it to 0 instead:

if (isNaN(percentLoaded)) {
  percentLoaded = 0;
}

You can encapsulate this process by defining a custom percentLoaded property for the Sound and MovieClip classes. The following code should be added to the Sound.as file created in Chapter 13:

// The getPercentLoaded(  ) method returns the percent that has loaded as a whole // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required