xxxxxxxxxx
82
// Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/151-ukulele-tuner.html
// https://youtu.be/F1OkDTUkKFo
// https://editor.p5js.org/codingtrain/sketches/8io2zvT03
const model_url = 'https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models/models/pitch-detection/crepe/';
let pitch;
let mic;
let sum = 0;
let total = 0;
let calcAvg = false;
let error = 0;
function setup() {
createCanvas(400, 250);
audioContext = getAudioContext();
mic = new p5.AudioIn();
mic.start(listening);
createButton('Play Pitch').mousePressed(() => {
const osc = new p5.Oscillator();
osc.amp(0.5);
osc.freq(440);
osc.start();
calcAvg = true;
setTimeout(() => {
osc.stop(0);
calcAvg = false;
//console.log(abs(sum / total - 440) * 100);
}, 1000);
});
}
function listening() {
console.log('listening');
pitch = ml5.pitchDetection(
model_url,
audioContext,
mic.stream,
modelLoaded
);
}
function draw() {
background(0);
const tempError = abs(sum / total - 440) * 100;
if (!isNaN(tempError)) {
error = tempError;
}
fill(255);
textAlign(CENTER, CENTER);
textSize(64);
text(error.toFixed(2), 200, 125);
if (!calcAvg) {
sum = 0;
total = 0;
}
}
function modelLoaded() {
console.log('model loaded');
pitch.getPitch(gotPitch);
}
function gotPitch(error, frequency) {
if (error) {
console.error(error);
} else {
//console.log(frequency);
if (frequency && calcAvg) {
sum += frequency;
total++;
}
pitch.getPitch(gotPitch);
}
}