AudioThread audioThread;
float[] wt;
float phase;
float dPhase;
float amplitude;
void setup() {
size(500,400, P2D);
// fill up a wavetable (am array)
// with a single cycle of the sin function
wt = new float[44100];
int N = wt.length;
for (int n = 0; n < N; n++){
wt[n] += sin(TWO_PI / (float) N * (float) n);
}
// phase dictates where we are in teh wavetable
phase = 0;
amplitude = 0;
// dphase dictaes how much we move by each time we read
// a value from the eavetable
dPhase = 200;
// Create the AudioThread object, which will connect to the audio
// interface and get it ready to use
audioThread = new AudioThread();
// Start the audioThread, which will cause it to continually call 'getAudioOut' (see below)
audioThread.start();
}
void draw() {
background(255);
fill(0);
if (mousePressed){
amplitude = 0;
}
else {
amplitude = 1;
}
}
// this function gets called when you press the escape key in the sketch
void stop(){
// tell the audio to stop
audioThread.quit();
// call the version of stop defined in our parent class, in case it does anything vital
super.stop();
}
// this gets called by the audio thread when it wants some audio
// we should fill the sent buffer with the audio we want to send to the
// audio output
void generateAudioOut(float[] buffer){
for (int i=0;i<buffer.length; i++){
// write the value from the wavetable into
// the buffer so it can be sent to the soundcard.
buffer[i] = wt[(int)phase] * amplitude;
// increase the phase, using modulo
// to wrap it back round to zero so
// we don't go out of the bounds of the wt array.
phase = (phase + dPhase) % wt.length;
}
}