xxxxxxxxxx
113
let mic;
let amplitude;
let ampMin = 0;
let ampMax = 0.05;
// Sound classification variables
let classifier;
let predictedSound = "listening";
let confidence = 0;
let confidenceThreshold = 0.5;
// Teachable Machine model URL - Replace with your model here:
let soundModelURL = "https://teachablemachine.withgoogle.com/models/qH19IouyB/";
// Visuals variables
let x, y;
let s = 5;
let speed = 3;
let colorPalette = ["#0794cd", "#fd40a9", "#35d528", "#fee712", "#ffac49", "#ff6f7d"];
let currentColor = colorPalette[4];
// Map sound labels to specific colors
// Adjust these keys to match the labels provided by your model.
let soundColorMap = {
"Clap": "#0794cd",
"Voice": "#fd40a9",
"Knocking": "#35d528",
"Ukulele": "#fee712",
"Background Noise": "#ffac49",
};
function preload() {
// Load the sound classifier model
classifier = ml5.soundClassifier(soundModelURL);
}
function setup() {
createCanvas(600, 400);
mic = new p5.AudioIn();
mic.start();
classifier.classifyStart(gotResult);
x = width / 2;
y = height / 2;
background(50);
}
function draw() {
// Get the current amplitude level
amplitude = mic.getLevel();
// Map amplitude to speed and size (clamped)
speed = map(amplitude, ampMin, ampMax, 5, 20, true);
s = map(amplitude, ampMin, ampMax, 5, 30);
let transColor = color(currentColor);
transColor.setAlpha(50);
stroke(currentColor);
fill(transColor);
// Store the previous position
let prevX = x;
let prevY = y;
// Update position with boundary checks
if (x < 0) {
x += 100;
} else if (x > width) {
x -= 100;
} else if (y < 0) {
y += 100;
} else if (y > height) {
y -= 100;
} else {
x += random(-speed, speed);
y += random(-speed, speed);
}
// If the classified sound is "Background Noise", draw a line; otherwise draw a circle.
if (predictedSound === "Background Noise" || predictedSound === "listening") {
line(prevX, prevY, x, y);
} else {
circle(x, y, s);
}
print(predictedSound);
}
function gotResult(results) {
if (results.length > 0) {
let newConfidence = results[0].confidence;
let newSound = results[0].label;
// Only update if confidence exceeds the threshold and the sound has changed
if (newConfidence > confidenceThreshold && newSound !== predictedSound) {
predictedSound = newSound;
confidence = newConfidence;
// Update currentColor using the mapping. If the sound is not in the mapping, use a default color.
if (soundColorMap.hasOwnProperty(predictedSound)) {
currentColor = soundColorMap[predictedSound];
} else {
currentColor = colorPalette[0];
}
}
}
}
function mousePressed() {
save("workshop.png");
}