Create colored circle based on midi note

Here is one method of changing the note color and location using mousePressed():

let c; // note color
let noteX = 0;
let noteY = 0;
let midiNotes = [60, 61, 62, 63];
let noteIndex = 0;
let midiVal, freq;

function lineGrid() {
  for(let k = 0; k < 5; k++) {
   lineY = 100 + k*(30);
   line( 30, lineY, width - 60, lineY);
  }
 }

function displayNote(){ 
  fill(c);
  circle(noteX, noteY, 20);
}

function setup() {
  let cnv = createCanvas(400, 400);  
  cnv.mousePressed(startSound);
  osc = new p5.TriOsc();
  env = new p5.Envelope();   
}

function draw() {
  background(255);
  fill(0);
  stroke(0);
  lineGrid();
  text('tap to play', 10, 20);
  if (midiVal) {
    text('MIDI: ' + midiVal, 10, 40);
    text('Freq: ' + freq, 10, 60);
    displayNote();
  }
 
}

function startSound() {
  // see also: userStartAudio();
  osc.start();

  midiVal = midiNotes[noteIndex % midiNotes.length];
  freq = midiToFreq(midiVal);
  osc.freq(freq);
  env.ramp(osc, 0, 1.0, 0);

  noteIndex++;
}

function mousePressed() {
 // console.log("note = " + midiVal);
  switch(midiVal){
    case 60: c = color('rgb(0,255,0)'); 
      noteX = 100; noteY = 220;
      break;
    case 61: c = color('rgb(255,0,0)');
      noteX = 130; noteY = 190;
      break;
    case 62: c = color('rgb(0,0,255)');
      noteX = 160; noteY = 160;
      break;
    case 63: c = color('rgb(0,255,255)');
      noteX = 190; noteY = 130;
      break;
  }
//  console.log("color = " + c);
  
}
1 Like