xxxxxxxxxx
75
let vol = 0.0;
let mic;
let pitch;
let audioContext;
let midiNum;
let volhistory = [];
const model_url = 'https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models/models/pitch-detection/crepe/';
const keyRatio = 0.58;
const scale = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
let currentNote = '';
let colors = [];
function setup() {
createCanvas(600, 400);
audioContext = getAudioContext();
mic = new p5.AudioIn();
mic.start(startPitch);
//Change the colorMode to HSB
colorMode(HSB); //360,100,100,1.0
//Define the color pallet
for(let i = 0; i < scale.length; i++) {
let newColor = color(i*360/scale.length, 50, 100, 0.9);
colors.push(newColor);
}
stroke(0,0,0,0.5);
background(0);
}
function startPitch() {
pitch = ml5.pitchDetection(model_url, audioContext , mic.stream, modelLoaded);
}
//Load the model and get the pitch
function modelLoaded() {
select('#status').html('Model Loaded');
getPitch();
}
//Draw on the canvas
function draw() {
//Use the volume from the microphone to control the size
vol = mic.getLevel();
// ellipse(mouseX, mouseY, vol*500);
volhistory.push(midiNum)
stroke(255);
noFill();
beginShape();
for (let x = 0; x < volhistory.length; x ++) {
var h = map(volhistory[i],0,1,height,0);
vertex(i,h);
}
if (volhistory.length>width){
volhistory.splice(0,1)
}
endShape();
}
//Get the pitch, find the closest note and set the fill color
function getPitch() {
pitch.getPitch(function(err, frequency) {
if (frequency) {
midiNum = freqToMidi(frequency);
currentNote = scale[midiNum % 12];
fill(colors[midiNum % 12]);
select('#noteAndVolume').html('Note: ' + currentNote + " - volume " + nf(vol,1,2));
}
getPitch();
})
}