PixelBoob / 8 posts / categories / 0 comments / feed / comments feed

Storing Sound

While most applications that use synthesized audio produce it on the fly, I wanted the opposite for Nycto. As the game environment is constant every time around (at least within reason) the sounds that entities make shouldn’t change too much. Plus, this means the audio can be pregenerated before the game begins and unnecessary calculations can be avoided.

For this to work, there are a couple of functions. First, one that generates the sound – a sine wave here:

public function generateSound():ByteArray
{
	var sound:ByteArray = new ByteArray();

	for(var i:int=0; i<16000; i++)
	{
		var sample:Number = Math.sin((Number(i)/Math.PI/2))*0.25;
		sound.writeFloat(sample);
		sound.writeFloat(sample);
	}

	return sound;
}

Then a segment in the game entity to prepare and play the sound, given the ByteArray as soundData:

var sound:Sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, this.handleSampleData);
this.soundData.position = 0;
this.soundChannel = sound.play();

And finally, a SAMPLE_DATA listener to play back the sample:

private function handleSampleData(event : SampleDataEvent) : void
{
	for(var i:int=0; i<4096*2; i++)
	{
		if(this.soundData.bytesAvailable)
		{
			event.data.writeFloat(this.soundData.readFloat());
		}
	}
}

This provides 4096 samples per channel – 8192 in stereo, which is the maximum we can provide. Once the end of the data is reached and the number of samples goes below 512, the sound will stop automatically.

No comments

Leave a comment