xxxxxxxxxx
83
// Sing/whistle different tones and see their relationship with the synth tone
let synth1 = new Tone.Synth({
"volume": -5,
"oscillator": {
"type": "sine",
"phase": 0
}
});
analyzer1 = new Tone.Waveform(256);
synth1.connect(analyzer1);
synth1.toMaster();
let mic = new Tone.UserMedia();
let analyzer2 = new Tone.Waveform(256);
mic.connect(analyzer2);
mic.open();
//Melodies
let ml = new Tone.Loop(melodyLoop, "4n");
let fundamental = 261.6*2; // middle C
let factors;
// C D E F G A B C
// ratios : 1/1, 9/8, 5/4, 4/3, 3/2, 5/3, 15/8, 2/1
// intervals: unison, 2nd, 3rd, 4th, 5th, 6th, 7th, octave
// ordered by decreasing consonance (perception varies)
// let factors = [1/1, 2/1, 3/2, 4/3, 5/4, 5/3, 9/8, 15/18];
// which gives us:
// unison, octave, fifth, fourth, third, sixth, second, seventh
function melodyLoop(time) {
let p = random();
if (p < 0.9) {
let pos = 0;
// a random melody in this scale
// let pos = floor(random(0, factors.length));
let note1 = fundamental * factors[pos];
synth1.triggerAttackRelease(note1, "4n", time);
}
}
// Start
function mouseClicked() {
if (Tone.context.state !== 'running') {
Tone.context.resume();
}
Tone.Transport.start();
ml.start();
}
let label;
let slider;
function setup() {
createCanvas(400, 400);
factors = [1 / 1, 2 / 1, 3 / 2, 4 / 3, 5 / 4, 5 / 3, 9 / 8, 15 / 8];
}
function draw() {
background(0);
let waveform1 = analyzer1.getValue();
let waveform2 = analyzer2.getValue();
strokeWeight(2);
noFill();
stroke(255);
beginShape();
for (let i = 0; i < waveform1.length; i++) {
let x = map(waveform1[i], -1, 1, 0, width);
let y = map(waveform2[i], -1, 1, height, 0);
vertex(x, y);
}
endShape();
}