xxxxxxxxxx
69
// A demonstration of the ml5.soundClassifier using a pre-trained set
// of speech commands (SpeechCommands18w), including: the ten digits from "zero" to "nine",
// "up", "down", "left", "right", "go", "stop", "yes", "no", as well as the
// additional categories of "unknown word" and "background noise"."
//
// By Jon Froehlich
// http://makeabilitylab.io/
//
// See:
// - Official documentation:
// https://learn.ml5js.org/#/reference/sound-classifier
// - Coding Train video:
// https://youtu.be/cO4UP2dX944
let soundClassifier;
let classificationResults;
function preload(){
// the default probabilityThreshold is 0
let options = { probabilityThreshold: 0.8 };
soundClassifier = ml5.soundClassifier('SpeechCommands18w', options);
}
function setup() {
createCanvas(400, 400);
soundClassifier.classify(onNewSoundClassified);
noLoop();
}
function draw() {
background(0);
fill(0, 240, 0);
if(classificationResults){
textSize(100);
textStyle(BOLD);
let strWidth = textWidth(classificationResults[0].label);
text(classificationResults[0].label, width / 2 - strWidth / 2, height / 2);
}
let textHeight = 14;
textSize(textHeight);
textStyle(NORMAL);
fill(0, 240, 0, 100);
let xNum = 5;
let xLabel = 25;
let xConf = 150;
let y = 15;
let resultNum = 1;
if(classificationResults){
for(let result of classificationResults){
text(nf(resultNum, 2), xNum, y);
text(result.label, xLabel, y);
text(result.confidence, xConf, y);
y += textHeight;
resultNum++
}
}
}
function onNewSoundClassified(error, results){
// Display error in the console
if (error) {
console.error(error);
}
classificationResults = results;
redraw();
}