Array

Playing Sounds, Displaying Progress

Must Read

Admin
Admin
Just post!

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:

sound.play(3000, 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:

import flash.media.SoundChannel;
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 = sound.play();
channel.addEventListener(Event.SOUND_COMPLETE, playComplete);
}
function playComplete(event:Event):void {
event.target.removeEventListener(Event.SOUND_COMPLETE, 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;
import flash.events.TimerEvent;

var channel:SoundChannel;
var sound:Sound;
// load sound
// on sound loaded
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showProgress);
channel = sound.play();
channel.addEventListener(Event.SOUND_COMPLETE, playComplete);
timer.start();
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;
trace(progress);
}

- Advertisement -

Latest News

Elevate Your Bentley Experience: The Bespoke Elegance of Bentayga EWB by Mulliner

Bentley Motors redefines the essence of bespoke luxury with the introduction of the Bentayga EWB's groundbreaking two-tone customization option—a...
- Advertisement -

More Articles Like This

- Advertisement -