xxxxxxxxxx
106
// Ideated and coded by Jean-Denis Theriault - KCJ
let soundModel = 'https://teachablemachine.withgoogle.com/models/rj4en0d8Y/model.json';
const options = {
probabilityThreshold: 0.95
};
console.log('Loading the sound classifier ...')
const classifier = ml5.soundClassifier(soundModel, options, modelReady);
let doorbellSound;
let doorbellOff;
let doorbellOn;
let doorbellActivated = false;
let doorbellFlashing = false;
let detectionNumber = 0;
function setup() {
doorbellSound = loadSound('sounds/Doorbell.wav', soundsLoaded);
createCanvas(800, 616);
doorbellOff = loadImage('images/AI_Doorbell_03.jpg');
doorbellOn = loadImage('images/AI_Doorbell_04.jpg');
createDiv();
createSpan('<br>');
button = createButton('Ring Doorbell');
button.mousePressed(ringDoorbell);
noLoop();
}
function draw() {
image(doorbellOff, 0, 0);
}
async function ringDoorbell() {
doorbellSound.play();
}
async function displayImages() {
if (doorbellActivated) {
if (!doorbellFlashing) {
doorbellFlashing = true;
for (let i = 0; i < 5; i++) {
image(doorbellOn, 0, 0);
await sleep(1000);
image(doorbellOff, 0, 0);
await sleep(1000);
}
doorbellFlashing = false;
}
} else {
image(doorbellOff, 0, 0);
}
}
function classifierFeedback(error, result) {
let label = result[0].label;
let confidence = result[0].confidence;
detectionNumber++;
printFeedback(label, confidence);
if (label === 'Doorbell') {
doorbellActivated = true;
} else {
doorbellActivated = false;
}
displayImages();
}
function modelReady() {
console.log('The sound classifier is loaded.')
ready = true;
classifier.classify(classifierFeedback);
}
function soundsLoaded() {
print('Sounds loaded.');
}
function printFeedback(label, confidence) {
confidence = Math.round((confidence * 100) * 100) / 100
print(`${detectionNumber}- Sound detected: "${label}". Confidence : ${confidence}%`);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}