This code uses the Minim library, which makes it possible to play sounds from Processing.
First I downloaded a bunch of piano notes from freesound.org, and I added them to my sketch as files named 0.mp3, 1.mp3, 2.mp3, etc.
Then I looked at Minim’s documentation to find the code that would load and play the sound files.
import ddf.minim.Minim;
import ddf.minim.AudioPlayer;
Minim minim;
AudioPlayer[] notes = new AudioPlayer[73];
void setup()
{
minim = new Minim(this);
for (int i = 0; i < notes.length; i++) {
notes[i] = minim.loadFile("notes/" + i + ".mp3");
}
frameRate(2);
}
void draw(){
background(0);
int i = int(random(notes.length));
notes[i].rewind();
notes[i].play();
}
I load the sound files into an array, and then I play a random note two times per second. The result is a random “song” that sounds like this:
The sketch, including the sound files, can be downloaded here.
keyPressed() function to turn your keyboard into a piano.