Looping Sound in Flex and AIR

This is a short example of how to play an audio clip and loop it in Flex, and works with AIR. Some of this code is taken from the Sound class example in the Adobe Flex Language Reference docs.

You can paste this into pretty much any function, like an init():

var soundReq:URLRequest = new URLRequest("someSound.mp3"); 
var sound:Sound = new Sound(); 
var soundControl:SoundChannel = new SoundChannel(); 
sound.addEventListener(Event.COMPLETE, completeHandler);
sound.addEventListener(Event.ID3, id3Handler);
sound.addEventListener(IOErrorEvent.IO_ERROR, ioSoundErrorHandler);
sound.addEventListener(ProgressEvent.PROGRESS, progressHandler);
sound.load(soundReq); 
soundControl = sound.play(0, int.MAX_VALUE);


Notice the line:
sound.play(0, int.MAX_VALUE);
The second parameter is the number of times to loop. Set it to zero to play the sound one time. There’s no real way (that I have found) to play the audio infinite times, so I put in int.MAX_VALUE which is a 32-bit signed integer of the value 2,147,483,647. Sure this won’t loop forever, but given a one second audio clip it would loop for about 68 years!

Here’s the handlers to go along with it:

private function completeHandler(event:Event):void {
    trace("completeHandler: " + event);
}
 
private function ioSoundErrorHandler(event:Event):void {
    trace("ioSoundErrorHandler: " + event);
}
 
private function id3Handler(event:Event):void {
    trace("id3Handler: " + event);
}
 
private function progressHandler(event:ProgressEvent):void {
    trace("progressHandler: " + event);
}

I’m still new to Flex so if anyone notices anything that isn’t right, please let me know. Also if anyone is looking for a decent BlazeDS tutorial, I’ve found one here. Also been reading Programming Flex 3: The Comprehensive Guide to Creating Rich Internet Applications with Adobe Flex which isn’t bad, if anyone else recommends a book let me know.


Leave a Reply