Skip to content

Instantly share code, notes, and snippets.

@Nutrox
Created December 11, 2010 16:38
Show Gist options
  • Save Nutrox/737452 to your computer and use it in GitHub Desktop.
Save Nutrox/737452 to your computer and use it in GitHub Desktop.
AS3 Oscillator Class
package nx.audio {
/**
*/
public class Oscillator implements ISampleGenerator {
private static const WAVEFORM_PULSE:uint = Waveform.PULSE;
private static const WAVEFORM_SAWTOOTH:uint = Waveform.SAWTOOTH;
private static const WAVEFORM_SINE:uint = Waveform.SINE;
private static const WAVEFORM_TRIANGLE:uint = Waveform.TRIANGLE;
private static const PI2:Number = Math.PI * 2.0;
private static const SAMPLE_TIME:Number = 1.0 / 22050.0;
public var waveform:uint = WAVEFORM_PULSE;
public var frequency:Number = 440.0;
public var amplitude:Number = 0.5;
public var phaseShift:Number = 0.0;
public var pulseWidth:Number = 0.5;
public var frequencyModulator:Modulator = null;
public var amplitudeModulator:Modulator = null;
public var pulseWidthModulator:Modulator = null;
/**
*/
public function Oscillator() {
}
/**
*/
public function generateSamples( time:Number, output:Vector.<Number> ):void {
var f:Number = frequency;
var a:Number = amplitude;
var w:Number = pulseWidth;
var t:Number = 0.0;
var s:Number = 0.0;
var i:uint = 0;
var n:uint = output.length;
var pulse:Boolean = waveform == WAVEFORM_PULSE;
var sawtooth:Boolean = waveform == WAVEFORM_SAWTOOTH;
var sine:Boolean = waveform == WAVEFORM_SINE;
var triangle:Boolean = waveform == WAVEFORM_TRIANGLE;
while( i < n ) {
t = ( 1.0 / f ) * ( ( time + f * phaseShift ) % f );
if( pulse ) {
s = ( t < w ? 1.0 : -1.0 ) * a;
}
else if( sawtooth ) {
s = ( -2.0 * t + 1.0 ) * a;
}
else if( sine ) {
s = Math.sin( PI2 * t ) * a;
}
else if( triangle ) {
s = ( t < 0.5 ? 4.0 * t - 1.0 : -4.0 * t + 3.0 ) * a;
}
output[ i ++ ] += s;
output[ i ++ ] += s;
if( frequencyModulator ) {
f += 19980.0 * frequencyModulator.sample( time );
f = f < 20.0 ? 20.0 : f > 20000.0 ? 20000.0 : f;
}
if( amplitudeModulator ) {
a += 1.0 * amplitudeModulator.sample( time );
a = a < 0.0 ? 0.0 : a > 1.0 ? 1.0 : a;
}
if( pulseWidthModulator ) {
w += 1.0 * pulseWidthModulator.sample( time );
w = w < 0.0 ? 0.0 : w > 1.0 ? 1.0 : w;
}
time += SAMPLE_TIME;
}
}
} // EOC
}
@HamDer
Copy link

HamDer commented Oct 27, 2011

Hi, my project cant find the IsampleGenerator interface? How do i get it working?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment