Bits & Bytes

Generating Sounds in Actionscript 3.0

This program shows how to generate and play a sound. The generated sound is in the form of a sine wave, and it plays whenever the screen is clicked. Left-click the box above to hear the sound play.

The entire code to generate the sound is shown below. The first three lines just output the message “Click To Play.” The next two lines create a Sound object and an integer for the time. The two lines after that set callbacks for generating sound and responding to mouse clicks.

The rest of the program consists of the PlaySound() and Generator() functions. The PlaySound() function initializes the integer that keeps track of the sample time to 0 and then calls play() on the Sound object. The Generator() function writes 8192 samples at a time for the left and right channels; the generated sound is a sine wave that lasts half of a second, since sounds have 44100 samples per second.

// Output the initial instructions to user
var qInstructions:TextField = new TextField();
qInstructions.text = "Click To Play";
addChild(qInstructions);

var qSound:Sound = new Sound();
var iTime:int = 0;

qSound.addEventListener(SampleDataEvent.SAMPLE_DATA, Generator);
stage.addEventListener(MouseEvent.CLICK, PlaySound);

function PlaySound(e:Event):void {
	iTime = 0;
	qSound.play();
}

function Generator(event:SampleDataEvent):void {
	for (var i:int = 0; i < 8192; ++i) {
		// Play for half of a second
		if (iTime >= 22050) {
			return;
		}
		event.data.writeFloat(Math.sin(iTime/25));
		event.data.writeFloat(Math.cos(iTime/25));
		++iTime;
	}
}

Tags: , , , , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.