FFT freeze with on and off

I set up a basic on/off switch for an FFT analyzer GUI for the signal from AudioIn. Works fine when I turn it on the first time, but when I turn it off and turn it back on, the FFT GUI freezes. Any suggestions on how to fix (code below)? Thanks!

var mic, fft;
var soundOn = false;


function setup() {
  createCanvas(400,400);
  noStroke();
  background(0,255,0);

  mic = new p5.AudioIn();
  mic.start();
  fft = new p5.FFT();
  fft.setInput(mic);

}



function mousePressed() {
  if (soundOn == false) {
    mic.connect();
    soundOn = true;
    background(0,255,255);
    } else {
    mic.disconnect();
    soundOn = false;
    background(0,255,0);
  }
}

function draw() {
  if(soundOn == true) {
  background(200);
   var spectrum = fft.analyze();

   beginShape();
   vertex(0, height);
   for (i = 0; i<spectrum.length; i++) {
    vertex(i, map(spectrum[i], 0, 255, height, 0) );
   }
   endShape();
} 

}

Answers

  • Answer ✓

    You need to format your code. Edit your post, highlight your code and hit ctrl+o,

    Regarding your question, you need to check what is happening behind the scenes when you call mic.disconnect(). Notice you link mic to your fft object in your setup function. However, your mousepressed function interacts with your mic object but neglects the fft object (which is linked to your mic object)

    When you activate the mic, associate this object to your fft object. Does this solve your problem?

    function mousePressed() { 
      if (soundOn == false) { 
        mic.connect(); 
        fft.setInput(mic);  //// **** Changed: added!
        soundOn = true; 
        background(0, 255, 255);
      } else { 
        mic.disconnect(); 
        soundOn = false; 
        background(0, 255, 0);
      }
    }
    

    Kf

  • Thanks, yes it works now, and thank you for the heads up about formatting in the forum;

Sign In or Register to comment.