I want to save the picture when the volume is greater than a certain level, but the current code will save many pictures continuously. How can I save only one picture?
let mic;
function setup() {
createCanvas(400, 400);
mic = new p5.AudioIn();
mic.start();
}
function draw() {
background(220);
let micLevel = mic.getLevel();
let y = height - map(micLevel, 0, 1, 0, height);
circle(width / 2, y, 30);
if(micLevel > 0.5) save(frameCount + '.png');
}
Just add a variable to track if you’ve saved yet. Only save if that variable is false and set it to true once you save:
let mic;
function setup() {
createCanvas(400, 400);
mic = new p5.AudioIn();
mic.start();
}
let saveTriggered = false;
function draw() {
background(220);
let micLevel = mic.getLevel();
let y = height - map(micLevel, 0, 1, 0, height);
circle(width / 2, y, 30);
if(micLevel > 0.5 && !saveTriggered) {
saveTriggered = true;
save(frameCount + '.png');
}
// TODO: add some condition to reset saveTriggered to false? maybe if the mic has been less than some threshold for a certain period of time?
}
Nice. One small change you might consider: always reset saveThreshold to 0 when micLevel > 0.5, that way if you have sustained loud noise it won’t trigger a re-save after 60 * 3 frames (~three seconds):
let mic;
let saveTriggered = false;
let saveThreshold = 0;
function setup() {
createCanvas(400, 400);
mic = new p5.AudioIn();
mic.start();
}
function draw() {
background(220);
let micLevel = mic.getLevel();
let y = height - map(micLevel, 0, 1, 0, height);
circle(width / 2, y, 30);
if(micLevel > 0.5 && ) {
if (!saveTriggered) {
saveTriggered = true;
save(frameCount + '.png');
}
saveThreshold = 0;
}
saveThreshold++;
// Wait for 3 seconds of quiet before re-enabling the save function
if(saveThreshold > 60*3) {
saveTriggered = false;
}
// console.log(micThreshold);
}