H3XED

How-to: Streaming MP3/Sound Length in Flash Actionscript 3

Feb 19, 2010   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
While creating a dynamic music player for the web in flash (AC3) I ran across a bit of an issue. When attempting to get the length of a song using the .length function, flash only returns the length of what it has loaded so far. Until the sound is fully loaded, flash is unable to tell you the length in seconds of that sound file. I found a solution that works well and doesn't rely on the length being manually inputted or pulled from the ID3 tags.

Utilizing Actionscript 3's .bytesTotal and .bytesLoaded functions, we can obtain the total file size of the sound file in bytes and how many bytes have been loaded thus far. Then using the .length function we can obtain the length in seconds that have been loaded. After that it's just a quick math equation and we get the total length of the song in milliseconds.

soundLength = mySound.length / mySound.bytesLoaded * mySound.bytesTotal
Keep in mind that the total seconds won't be completely accurate for the first 1%~ of the sound. Just have it display a loading message first. For fast connections they likely won't even notice it.

[Update: Prior to any data being loaded (while bytesLoaded equals 0), an error will return. To fix this, use a condition statement to check that bytesLoaded is greater than 0 before displaying sound length information]

Here's an example:

// Request the path to the sound file
var myRequest:URLRequest = new URLRequest(PATH);

// Create your sound variable
var song:Sound = new Sound();

// Create variable that will hold the total length
var songLen:Number;

// Load the actual sound from the request URL
song.load(myRequest);

// Run the math equation
songLen = song.length / song.bytesLoaded * song.bytesTotal;

// Divide by 1000 to get seconds and round
songLen = Math.round(songLen / 1000);
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter