import processing.core.*; 
import processing.xml.*; 

import processing.net.*; 
import ddf.minim.*; 

import java.applet.*; 
import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.text.*; 
import java.util.*; 
import java.util.zip.*; 
import java.util.regex.*; 

public class SoundServer3 extends PApplet {

 





Server s; 

Minim minim;
AudioInput in;

public void setup()
{
  size(512, 200, P2D);
 

  s = new Server(this, 4444);
  
 
  minim = new Minim(this);
  minim.debugOn();
  
  // get a line in from Minim, default bit depth is 16
  in = minim.getLineIn(Minim.STEREO, 512);
}


 
 
  Boolean bool = false;
public void draw()
{
  //get a client if they are sending something
  Client client=s.available();
 
  if(client!=null)
  {
    try
    {
      //get the bytes from the stream
      ByteArrayInputStream byte_in = new ByteArrayInputStream (client.readBytes());
      //send it to a data input stream so we can get some variables out of it
      DataInputStream data_in = new DataInputStream (byte_in);
 
      //get the data
      bool=data_in.readBoolean();
      float inc=data_in.readFloat();
      
      println(bool);
      println(inc);
    }
    catch(IOException e)
    {
    
      println("ERROR: "+e);
    }
  }
 
  if(bool)
  {
      
      
      try{
        
        ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
       
        DataOutputStream data_out = new DataOutputStream(byte_out);

        for(int i = 0; i < 512; i++)
        {
         data_out.writeFloat((float)((in.left.get(i))));
          
        }
        
        for(int i = 0; i < 512; i++)
        {
           data_out.writeFloat((float)((in.right.get(i))));
        }
  
        s.write(byte_out.toByteArray());
      }catch (IOException e){
          
         println("ERROR: "+e);
      }
      
  }
}



public void stop()
{
  // always close Minim audio classes when you are done with them
 in.close();
  minim.stop();
  
  super.stop();
}
 

  static public void main(String args[]) {
    PApplet.main(new String[] { "--bgcolor=#ffffff", "SoundServer3" });
  }
}
