import krister.Ess.*;

Channel mySound;

Channel[] mySound;  'is this redundant


int writeSamplesSize;

int writeUpdateTime;

int lastCue;


byte[] drawBuffer;

int drawBufferLoad;

int drawBufferStartTime;


void setup() {

  size(256,200);

    

  // start up Ess


  Ess.start(this);


  mySound=new Channel[6]

  //("Beat01.aif");

  mySound.normalize();

  

  mySound.setupFFT(512);


  mySound.updateWriteSamples=true;


  writeSamplesSize=mySound.writeSamples.length;

  drawBuffer=new byte[writeSamplesSize*2];


  // based on our sampleRate and writeSamplesSize, figure out how often writeSamples is updated


  writeUpdateTime=mySound.ms(writeSamplesSize);


  framerate(30);

  noSmooth();

  

  mySound[1] = "Beat01.aif"

  mySound[2] = "Beat02.aif"

  mySound[3] = "Beat04.aif"

  mySound[4] = "Beat23.aif"

  mySound[5] = "DrumKit01.aif"

  mySound[6] = "Drumkit13.aif"

}


void draw() {

  background(0,0,255);

  drawSpectrum();

  drawWriteSamples();

}


void drawSpectrum() {

  noStroke();


  mySound.loadSpectrum();


  for (int i=0; i<256; i++) {

    float temp=max(0,185-mySound.spectrum[i]*175);

    rect(i,temp+.5,1,height-temp+.5);

  }

}


void drawWriteSamples() {

  stroke(255);


  // first check to see if we are playing


  if (mySound.state==Ess.PLAYING) {

    if (mySound.cue!=lastCue) {

      // we have a new write buffer to copy


      switch (drawBufferLoad) {

        case -1:

        // fill front of drawBuffer


        System.arraycopy(mySound.writeSamples,0,drawBuffer,0,writeSamplesSize);

        break;

        case 0:

        // fill back of drawBuffer


        System.arraycopy(mySound.writeSamples,0,drawBuffer,writeSamplesSize,writeSamplesSize);

        break;

        default:

        // shift back of drawBuffer to front and fill back of draw buffer

        

        System.arraycopy(drawBuffer,writeSamplesSize,drawBuffer,0,writeSamplesSize);

        System.arraycopy(mySound.writeSamples,0,drawBuffer,writeSamplesSize,writeSamplesSize);

      }


      drawBufferLoad++;

      lastCue=mySound.cue;

      drawBufferStartTime=millis();

    }


    if (drawBufferLoad>0) {

      // interpolate between 0 and writeSamplesSize over writeUpdateTime


      int interp=(int)(((millis()-drawBufferStartTime)/(float)writeUpdateTime)*writeSamplesSize);


      for (int i=0;i<256;i++) {

        line(i,100-(mySound.getFrame(drawBuffer,i+interp)*(75.0/32767)),i+1,100-(mySound.getFrame(drawBuffer,i+1+interp)*(75.0/32767)));

      }

    }

  } else {

    line(0,100,255,100);

  }

}


void mousePressed() {

  if (mySound.state==Ess.PLAYING) {

    mySound.stop();

  } else {

    lastCue=-1;

    drawBufferLoad=-1;

    mySound.play(Ess.FOREVER);

  }

  

}


// clean up Ess before exiting


public void stop() {

  Ess.stop();

  super.stop();

}