Thursday, July 29, 2010

Sound class in Actionscript 3: Part 4

Today we're going to learn how to make a progress bar and how to find out when the song stopped playing.

To find out how much of the song has been played, we need to know the length and current position of the playback. An audio file's length is a property of the Sound class, while the current playback position is SoundChannel's property.

If you look at those two properties you will understand how to draw the bar, however there is a problem. The exact value of length isn't known until the file is fully downloaded. For example, if only 50% is loaded at the moment of a 4 minute file, it will show us that length is 2 minutes (keep in mind that both length and position return values in milliseconds).

However, we can find out the full length by dividing the current length by the fraction of the loaded sound relative to full sound. For example, if we divide 2 by 1/2 (same as multiply by 2) we see that 4 minutes is the initial length of our audio file.

Therefore, we can solve the problem with one line of code:

length /= percentBuffer

Now let's modify our previous progress bar code from the Part 2 (the one that shows how much of the song is loaded):

stage.addEventListener(Event.ENTER_FRAME, loop);
var mysound = new Sound(new URLRequest("song.mp3"));
var theChannel:SoundChannel
theChannel =;

var barwidth = 200
var barheight = 10

function loop (event:Event){
var loaded = mysound.bytesLoaded;
var total = mysound.bytesTotal;

if(total > 0){
// progress bar background
graphics.drawRect(20,20, barwidth, barheight);

var percentBuffer = loaded / total
var totalLength = mysound.length / percentBuffer
var percentPlayed = theChannel.position / totalLength

// loading progress bar
graphics.drawRect(20, 20, barwidth * percentBuffer, barheight);

// playback progress bar
graphics.drawRect(20, 20, barwidth * percentPlayed, barheight);

We can also tell when the sound stopped playing using a listener and Event.SOUND_COMPLETE, add this piece of code after the one above:

theChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);

function soundComplete(Event){
trace("sound finished playing!");}

Thanks for reading!


Sound class in Actionscript 3: Part 1
Sound class in Actionscript 3: Part 2
Sound class in Actionscript 3: Part 3
Sound class in Actionscript 3: Part 5
Sound class in Actionscript 3: Part 6


Anonymous said...

What do i do if i want to play more than one sound and use the same progress bar ???

Kirill Poletaev said...

You mean like, one sound after another? You might want to merge your sounds into one file for that.

Post a Comment