xxxxxxxxxx
53
// synth vars
let osc, envelope;
let notes = [];
// the amount of notes
let noteAmount = 8;
// the periods of the wave in the notes
let periods = 3.57;
// the highest and lowest midi note
let upper = 72;
let lower = 48;
// counter for note selection
let count = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
// The sinewave note array generator
for (var i=0; i<noteAmount; i++){
// get the amplitude value of a sinewave function based on
// index in note array and multiplied by periods
let a = Math.sin(i/noteAmount*Math.PI*periods);
// translate the amplitude -1/1 range to a note within
// upper/lower limits, floor to get an integer for MIDI
notes[i] = Math.floor((a * 0.5 + 0.5) * (upper-lower) + lower);
}
console.log('notes:', notes);
// setup a synth
osc = new p5.SinOsc();
envelope = new p5.Envelope();
envelope.setADSR(0.001, 0.2, 0, 0);
envelope.setRange(1, 0);
}
function draw() {
background(0);
// play a note every n-frames
if (frameCount % 12 === 0) {
// get the value from the note array and convert to frequency
let frequency = midiToFreq(notes[count]);
osc.freq(frequency);
osc.start();
envelope.play(osc, 0, 0.1);
// increment counter within note array length
count = (count + 1) % notes.length;
}
}