Here is the full code if you want to have a look:
Code:
/*
Use 1-8 on your keyboard to play tones in the C major scale
*/
import ddf.minim.*;
import ddf.minim.signals.*;
Minim minim;
AudioOutput out;
SineWave sine;
SineWave nullSine;
float freq = 0;
float amp = 1;
int keysPressed = 0;
int port = 30;
//c5-c6 major scale in hz
float[] tones = {523.25, 587.33, 659.26, 698.46, 783.99, 880.00, 987.77, 1046.50};
char keys[] = {'1','2','3','4','5','6','7','8'};
boolean keyStates[];
void setup()
{
size(300,100);
keyStates = new boolean[keys.length];
minim = new Minim(this);
out = minim.getLineOut(Minim.STEREO);
nullSine= new SineWave(0, 0, out.sampleRate());
sine = new SineWave(0, amp, out.sampleRate());
sine.portamento(port);
}
//determine which keys have been pressed
void keyPressed()
{
for(int i=0;i<keys.length;i++)
{
if(key == keys[i])
keyStates[i] = true;
}
}
//determine which keys have been released
void keyReleased()
{
for(int i=0;i<keys.length;i++)
{
if(key == keys[i])
keyStates[i] = false;
}
}
void draw()
{
background(100);
out.clearSignals();
out.addSignal(nullSine);
//adjust amplitude to avoid distortion with chords
keysPressed=0;
for(int i=0; i<keyStates.length; i++)
{
if(keyStates[i]) keysPressed++;
}
if(keysPressed == 0) amp = 1.0;
else amp=1.0/keysPressed;
for(int i=0; i<keyStates.length; i++)
{
if(keyStates[i])
{
out.addSignal(new SineWave(tones[i], amp, out.sampleRate()));
}
}
/*for(int i = 0; i < out.bufferSize() - 1; i++)
{
float x1 = map(i, 0, out.bufferSize(), 0, width);
float x2 = map(i+1, 0, out.bufferSize(), 0, width);
line(x1, 50 + out.left.get(i)*50, x2, 50 + out.left.get(i+1)*50);
line(x1, 150 + out.right.get(i)*50, x2, 150 + out.right.get(i+1)*50);
}*/
}
void stop()
{
out.close();
minim.stop();
super.stop();
}