xxxxxxxxxx
135
// 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 freq = 0;
let threshold = 1;
let sThreshold = 3;
let extFrame = false;
let notes = [{
note: 'A',
freq: 440,
next: null
},
{
note: 'E',
freq: 329.6276,
next: null
},
{
note: 'C',
freq: 261.6256,
next: null
},
{
note: 'G',
freq: 391.9954,
next: null
}
];
notes[3].next = notes[2];
notes[2].next = notes[1];
notes[1].next = notes[0];
let current = notes[3];
function setup() {
createCanvas(400, 250);
audioContext = getAudioContext();
mic = new p5.AudioIn();
mic.start(listening);
}
function listening() {
console.log('listening');
pitch = ml5.pitchDetection(
model_url,
audioContext,
mic.stream,
modelLoaded
);
}
function mousePressed() {
if (current.next) {
current = current.next;
} else {
extFrame = true;
}
}
function draw() {
background(0);
textAlign(CENTER, CENTER);
fill(255);
if (extFrame) {
text('Great!\nYou\'ve tuned your ukalele!', 200, 125);
noLoop();
} else {
textSize(32);
text(`Tune the ${current.note} string.`, 200, 212);
let diff = freq - current.freq;
// let amt = map(diff, -100, 100, 0, 1);
// let r = color(255, 0, 0);
// let g = color(0, 255, 0);
// let col = lerpColor(g, r, amt);
let alpha = map(abs(diff), 0, 100, 255, 0);
rectMode(CENTER);
fill(255, alpha);
stroke(255);
strokeWeight(1);
if (abs(diff) < sThreshold) {
fill(255, 255, 0);
}
if (abs(diff) < threshold) {
fill(0, 255, 0);
}
rect(200, 100, 200, 50);
stroke(255);
strokeWeight(4);
line(200, 150, 200, 180);
fill(255);
triangle(200, 146, 204, 154, 196, 154);
noStroke();
fill(255, 0, 0);
if (abs(diff) < sThreshold) {
fill(255, 255, 0);
}
if (abs(diff) < threshold) {
fill(0, 255, 0);
}
rect(200 + diff / 2, 100, 10, 75);
textSize(32);
text(freq.toFixed(2), 200, 40);
}
}
function modelLoaded() {
console.log('model loaded');
pitch.getPitch(gotPitch);
}
function gotPitch(error, frequency) {
if (error) {
console.error(error);
} else {
//console.log(frequency);
if (frequency) {
freq = frequency;
}
pitch.getPitch(gotPitch);
}
}