xxxxxxxxxx
114
let step = 0;
let x = 0,
y = 0,
prevx,
prevy;
let angle = 0;
let radius = 0;
let theta = 0;
let osc = [];
let env = [];
let notes = [41, 45, 48, 52, 53, 57, 60, 64, 65]; // Midi note numbers
// F A C E F A C E in two octaves if you want to play along
function setup() {
console.log("Start");
createCanvas(400, 400);
stroke(255);
background(0);
x = width / 2;
y = height / 2;
prevx = width / 2;
prevy = height / 2;
// Start the tone oscillators and envelopes
for (let i = 0; i <= 10; i++) {
if (i < 5) osc[i] = new p5.TriOsc();
else osc[i] = new p5.SinOsc();
osc[i].start();
osc[i].amp(0);
env[i] = new p5.Envelope(0.1, 0.7, 2, 0.1);
}
}
function playNote(note, duration, oscNum) {
osc[oscNum].freq(midiToFreq(note));
env[oscNum].play(osc[oscNum]);
}
function drawLine() {
// draws the sweeping line
let x = width / 2;
let y = height / 2;
for (i = 0; i < width * 0.7; i += 4) {
let posx = x + cos(theta) * i;
let posy = y + sin(theta) * i;
let col = get(posx, posy);
if (red(col) == 255 && green(col) == 255 && blue(col) == 0) {
//work out length of line
let length = sqrt((posx - x) * (posx - x) + (posy - y) * (posy - y));
let note = floor(map(length, 0, width / 2, 1, 8));
if (note != 1) playNote(notes[note], 20, note);
}
point(posx, posy);
}
theta += 0.002;
}
function drawSpiral() {
// draws the spiral with the prime dots
while (x < width || y < height) {
x = width / 2 + cos(angle) * radius;
y = height / 2 + sin(angle) * radius;
line(x, y, prevx, prevy);
prevx = x;
prevy = y;
if (isPrime(step)) {
fill(255, 255, 0);
noStroke();
circle(x, y, 5);
fill(255, 255, 255);
stroke(255, 255, 255);
}
step++;
angle += 0.1;
radius += 0.5;
}
angle = 0;
radius = 0;
prevx = width / 2;
prevy = height / 2;
step = 0;
x = width / 2;
y = height / 2;
}
function draw() {
background(0);
drawSpiral();
drawLine();
}
// Function to test if number is prime - From D Shiffman Ulam Spiral
function isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= sqrt(value); i++) {
if (value % i == 0) {
return false;
}
}
return true;
}