P5.js - How to save a single picture in the draw()

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?

Thank you for your help:)

https://editor.p5js.org/niu/sketches/OAEYNNHgC

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?
}
3 Likes

Thank you for your help,The idea of ​​setting saveTriggered to false is also great!

I completed the code to change safe Triggered to false :slight_smile:

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 && !saveTriggered) {
    saveTriggered = true;
    save(frameCount + '.png');
    saveThreshold = 0;
  }
  
  saveThreshold ++;
  
  // Time
  if(saveThreshold > 60*3) {
    saveTriggered = false;
  }
  // console.log(micThreshold);
}
1 Like

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);
}