xxxxxxxxxx
103
let oscillators;
let soundTestOscillator;
let startNote = "A5";
let startAmp = 0;
let delayTime = 7;
const THX_CHORD = [
"D2",
"D3",
"A3",
"D4",
"A4",
"D5",
"A5",
"D6",
"A6",
"D7",
"F#7",
];
const oscPort = new osc.WebSocketPort({
url: "ws://localhost:8081",
});
oscPort.on("message", (msg) => {
console.log("message", msg);
if (msg.address == "/chord/thx/single") {
// Select a random note for the THX chord
// How many computers need to run this sketch to get all
// the chord tones? 33 -> this is called the
// "coupon collector's problem".
const noteToPlay = random(THX_CHORD);
oscillators[0].start();
oscillators[0].freq(noteToFreq(noteToPlay), delayTime);
oscillators[0].amp(1, delayTime);
} else if (msg.address == "/chord/thx/multiple") {
// Each individual sketch will handle multiple voices
for (let i = 0; i < msg.args[0]; i++) {
const noteToPlay = random(THX_CHORD);
oscillators[i].start();
oscillators[i].freq(noteToFreq(noteToPlay), delayTime);
oscillators[i].amp(1, delayTime);
}
} else if (msg.address == "/chord/msg/single") {
// Get our notes from the message
// Notice similarity to /chord/thx/single
const noteToPlay = random(msg.args[0]);
oscillators[0].start();
oscillators[0].freq(noteToFreq(noteToPlay), delayTime);
oscillators[0].amp(1, delayTime);
} else if (msg.address == "/chord/msg/multiple") {
// Notice similarity to /chord/thx/multiple
for (let i = 0; i < msg.args[1]; i++) {
const noteToPlay = random(msg.args[0]);
oscillators[i].start();
oscillators[i].freq(noteToFreq(noteToPlay), delayTime);
oscillators[i].amp(1, delayTime);
}
} else if (msg.address == "/stop") {
for (let i = 0; i < oscillators.length; i++) {
oscillators[i].stop();
// and reset
oscillators[i].freq(noteToFreq(startNote));
oscillators[i].amp(startAmp);
}
}
});
oscPort.on("close", () => {});
oscPort.open();
function setup() {
createCanvas(400, 400);
soundTestOscillator = new p5.Oscillator();
// Make a new array given a number for length
oscillators = new Array(THX_CHORD.length);
// Then populate the array with new Oscillator instances
for (let i = 0; i < oscillators.length; i++) {
oscillators[i] = new p5.Oscillator("sawtooth");
}
// Set our starting note and starting volume
for (let i = 0; i < oscillators.length; i++) {
oscillators[i].freq(noteToFreq(startNote));
oscillators[i].amp(startAmp);
}
}
function draw() {
background(220);
}
function mousePressed() {
soundTestOscillator.start();
soundTestOscillator.freq(noteToFreq('C4'));
soundTestOscillator.amp(0.8, 0.1);
}
function mouseReleased() {
soundTestOscillator.amp(0, 0.5);
}