views:

47

answers:

1

is there common code available that produces square, triangle, sawtooth or any other custom waveforms using the math class?

below is a basic function that handles a SampleDataEvent and plays a middle-c (440 Hz) sine wave. i'd like to change the tone by incorporating square, triangle and other waves.

var position:int = 0;

var sound:Sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleDataHandler);
sound.play();

function sampleDataHandler(event:SampleDataEvent):void
    {
    for(var i:int = 0; i < 2048; i++)
        {   
        var phase:Number = position / 44100 * Math.PI * 2;
        position ++;

        var sample:Number = Math.sin(phase * 440);
        event.data.writeFloat(sample); // left
        event.data.writeFloat(sample); // right
        }
    }
+1  A: 

Wikipedia gives simple equations for the square, triangle, and sawtooth waves. Here are probably the simplest (which all have period 1):

square(t) = sgn(sin(2πt))
sawtooth(t) = t - floor(t + 1/2)
triangle(t) = abs(sawtooth(t))
BlueRaja - Danny Pflughoeft
hi BlurRaja. i'm having a bit of difficulty following your example. i'm afraid my math skills are not so great. how would you incorporate these new waveforms into the following basic sound sample: var sample:Number = Math.sin(phase * 440);i've updated my question to show this function.
TheDarkInI1978
particularly, i have no idea what 2πt means or how it should be substituted in AS3.
TheDarkInI1978
@TDI1978: 2πt means two times pi (3.141592...) times t (which is your variable, like sin(t)). [sgn](http://en.wikipedia.org/wiki/Sign_function) is the sign (-1 for negative, 0 for zero, +1 for positive), [floor](http://en.wikipedia.org/wiki/Floor_and_ceiling_functions) means round down, and [abs](http://en.wikipedia.org/wiki/Absolute_value) is the absolute value (remove the negative sign if the value is negative)
BlueRaja - Danny Pflughoeft