saveJSON with a for loop?

edited December 2016 in p5.js Library Questions

Hi there,

I'm trying to generate a JSON file by looping through arrays and it doesn't work.

Filling the arrays with the sound-function may be too late for the JSON object in the setup-function, but I don't know how to fix this problem (using a preload function doesn't make sense to me because the values are getting generated while the program runs).

Any ideas? Many thanks in advance for your help!

Here is my code:

var json;
var mic, fft;

var arrayVolume = [];
var arrayEnergy = [];
var arrayCentroid = [];

function setup() {
  frameRate(5);

  // new JSON object
 for(var i = 0; i < frameRate; i++){
    json = {}; 

    json.id = i;
    json.volume = arrayVolume[i];
    json.energy = arrayEnergy[i];
    json.centroid = arrayCentroid[i];

    saveJSON(json, 'sound.json');
  }

  // create input
  mic = new p5.AudioIn();
  fft = new p5.FFT();

  //start  input
  mic.start();
  fft.setInput(mic);
}


function draw() {
  // call functions
  sound();
}


function sound() {
   // get volume
  var vol = mic.getLevel();

  // analyze spectrum
  var spectrum = fft.analyze();
  var energy = fft.getEnergy("lowMid"); // bass, lowMid, mid, hightMid
  var centroid = fft.getCentroid();

  // push it in arrays
  arrayVolume.push(vol);
  arrayEnergy.push(energy);
  arrayCentroid.push(centroid)
}

Answers

  • it doesn't work

    What do you expect to happen, and what happens instead? Does the file not appear, or is it empty, or does it have the wrong contents?

    1. Don't base your loop on frameRate in setup() -- instead, set a variable to 5 and use that in both the loop and the call to frameRate().
    2. Did you mean to call saveJSON(json, 'sound.json') inside your loop, i.e. five times?
  • Did you mean to call saveJSON(json, 'sound.json') inside your loop, i.e. five times?

    thread title suggests he did 8)

    at best that's going to overwrite the first 4 lots of data with the 5th. you need to add a loop-specific suffix to the filename to separate the data.

  • Hey jeremydouglass and kooks, thanks so far for your comments! And outch, I just found a mistake: in the for-loop it is frameCount, not frameRate! But that is not the problem.

    I want to generate a JSON file that analyzes sound. One second of sound fills the file with five objects containing the id, volume, energy and centroid. With using the mic input of my computer and not a sound file, the arrays are getting bigger in real time. I want the .json-file to include all five objects per second until I stop the program. But how does this work? Do you understand my post now?

  • edited December 2016 Answer ✓

    Also don't use frameCount in a setup for loop!

    In the setup loop, frameCount=0: no frames have been drawn. Your loop will test i<0 and exit without ever running.

Sign In or Register to comment.