Will Perone

Removing the Gap in a looping sound in Flash using Actionscript

You probably noticed if you've tried to make any looping song in your Flash game that there's a gap between each loop.
[ Embed ( source = "song.mp3" ) ] private var Song:Class;      

var music:Sound = new Song();
music.play(0, int.MAX_VALUE); // retarded gap of silence between each loop
After some digging around, I noticed when I traced the length of the music it was actually longer then the actual song! The weird thing is, it's not even a nice number:
// The original wave file has 151846 samples at 44100 samples/sec -> length = 3.44321995 seconds
trace(music.length); // returns 3.526530612244898 seconds
Converting this to milliseconds we see that there's around an 83 millisecond gap added to the length of the song for some reason. After reading around the net, I came to understand this is because of how mp3 encoders/decoders work. There is apparently a solution if you have Adobe CS3 but I don't have $670 to buy it so I'm using Flash Develop. Here is how I got around it in plain old actionscript 3:
var timer:Timer;
var channel:SoundChannel;

timer = new Timer(music.length-83); // remove the silence gap at the end of the song added by Flash, you may need to tweak this depending on your mp3 encoder
timer.addEventListener("timer", function (e:Event):void { // hack to get around gap between loops
	channel= music.play();

var initialTimer:Timer = new Timer(0, 1); // hack to get around initial gap from playing the first time and the timer kicking in
initialTimer.addEventListener("timer", function (e:Event):void {
	channel= music.play();
	initialTimer = null;
To Stop the song you will also need to kill the timer:
Not exactly elegant but it works and for you CS3 users, it lets you actually embed the mp3 instead of a wav version of it... unless you have a slow computer, then the time between a frame can become too long for the timer to kick in often enough and this causes the gap to happen again.

gregrahn 27 21
Hey Will,
There is another work around that I've heard solves the gap problem. I am trying it on Zening music, but they have not yet implemented it so still not 100% sure. If you create the mp3 loop in Flash, then it should loop seamlessly in the game. The loops I made loop seamlessly when played in my browser so that's a good sign. I'l let you know if it works.

Jeds 2012/06/15100 27
AS3 is a very big shit
Robertha 2012/09/13 Contact Me3 23
And to clear something up, there is NOTHING vague about the mnaeing of the song. People only think so as they can not pick up on the obvious references to Christianity throughout the lyrics. There is no other mnaeing that can interpreted from this song
Rich 2013/12/170 0
Just so you know, MP3 encoding can add silence to BOTH the beginning and end of files, and it will change depending on the number bytes in the original material ... the solution is not as easy as this sadly :(

<- for private contact