Playing Sounds, Displaying Progress

Playing Sounds

In the earlier example, we used the play method. You can add some optional parameters to have more control over playback. The first parameter represents the starting position, the second parameter the number of times to loop the sound.

In this example, the sound starts at the three-second position and loops five times:, 5);

When it loops again, it starts at the same position, here the third second.

The Sound class does not dispatch an event when it is done playing. The SoundChannel class is used for that purpose, as well as for controlling sound properties such as volume and to stop playback. Create it when a Sound object starts playing. Each sound has its own channel:

var sound = new Sound();
sound.addEventListener(Event.COMPLETE, onLoaded);
sound.load(new URLRequest(“mySound.mp3”));
function onLoaded(event:Event):void {
sound.removeEventListener(Event.COMPLETE, onLoaded);
var channel:SoundChannel =;
channel.addEventListener(Event.SOUND_COMPLETE, playComplete);
function playComplete(event:Event):void {, playComplete);
trace(“sound done playing”);

Displaying Progress

There is no direct way to see playback progress, but you can build a timer to regularly display the channel position in relation to the length of the sound. The sound needs to be fully loaded to acquire its length:

import flash.utils.Timer;

var channel:SoundChannel;
var sound:Sound;
// load sound
// on sound loaded
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showProgress);
channel =;
channel.addEventListener(Event.SOUND_COMPLETE, playComplete);
function showProgress(event:TimerEvent):void {
// show progress as a percentage
var progress:int = Math.round(channel.position/sound.length*100);

Do not forget to stop the timer when the sound has finished playing:

function playComplete(event:Event):void {
channel.removeEventListener(Event.SOUND_COMPLETE, playComplete);
timer.removeEventListener(TimerEvent.TIMER, showProgress);

You do not know the length of a streaming audio file until it is fully loaded. You can, however, estimate the length and adjust it as it progresses:

function showProgress(event:TimerEvent):void {
var percentage:int = sound.bytesLoaded/sound.bytesTotal;
var estimate:int = Math.ceil(sound.length/percentage);
// show progress as a percentage
var progress:int = (channel.position/estimate)*100;