Play sound file and analyze it at same time - not working

edited November 2016 in p5.js Library Questions

HI, My goal is to analyze a sound file for the amplitude peaks. I can play the sound file once if I remove the draw loop from the code. If I put some of the code into a draw loop, the sound file runs every time I click the mouse. In the function call function playSoundFile(e), mySound.play() is in the line directly before var rms = analyzer.getLevel() The issue is that the level only gets grabbed once.

 `var flag = 0;
  var state = 0; // mousePress will increment from Record, to Stop, to Play
  var mic, recorder, soundFile, song, mySound, whatever;

  function setup() {
  createCanvas(800,600);
  background(250,120,35);
  textSize(28);
  fill(0, 152, 153);
  text('Enable mic and click the mouse to begin recording', 20, 50);
  mic = new p5.AudioIn();
  mic.start();
  recorder = new p5.SoundRecorder();  // create a sound recorder                                       
  recorder.setInput(mic);             // connect the mic to the recorder
  soundFile = new p5.SoundFile();
  analyzer = new p5.Amplitude();      // create a new Amplitude analyzer
  }

 function mousePressed() {
 switch(state){
   case 0: // look for mic recording something
    if (!mic.enabled){return;}
    recorder.record(soundFile);
    background(110,120,0);
    textSize(28);
    fill(0, 152, 153);
    text('Recording now! Click to stop.', 20, 100);
    state++;
    break;
case 1: // stop recording and send to sound file
  recorder.stop();
  background(0,0,0);
  background(0,120,0);
  textSize(28);
  fill(0, 152, 153);
  text('Stopped recording. Click to save.', 20, 100);
  console.log("case 1 flag is",flag);
  state++;
  break;
case 2:  // save sound file
  saveSound(soundFile, 'mySound.wav'); // save file
  console.log("case 2 flag is",flag);
  state++;
  break;
case 3:  // load sound file
  loadSoundFile();
  flag = 1 ;
  background(255,255,255);
  textSize(28);
  fill(0, 102, 153);
  text('click mouse one more time',20,70);
  console.log("case 3 flag is",flag);
  state++;
  break;
case 4:
  console.log("case 4 flag is",flag);
  state++;
  break;
 }
 }  

function loadSoundFile(){
textSize(28);
fill(0, 152, 153);
text("loadSoundFile",70,70);
mySound = loadSound('mySound.wav', playSoundFile, failSoundFile, whileLoading);
analyzer.setInput(mySound);            // patch the input to an volume analyzer
}

function playSoundFile(e){
text ("playSoundFile",90, 90);
mySound.setVolume(.1);
mySound.play();   
var rms = analyzer.getLevel();
console.log("this is soundLevel:", rms);
var soundLevel = rms.toFixed(4);
}

 /*function draw() {
  if (flag == 1){
  var rms = analyzer.getLevel();
  var soundLevel = rms.toFixed(4);
  console.log("this is soundLevel:", soundLevel);
  console.log("flag is 1");
  }
  else{
  }
  }
  }*/`
Sign In or Register to comment.