import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class testSound {
  public static float SAMPLE_RATE = 22050f;
  private static final int BITS_PER_SAMPLE = 16; // 16-bit audio
  
  private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767
  private static final int MONO = 1;
  private static final int STEREO = 2;

  private static final boolean LITTLE_ENDIAN = false;
  private static final boolean BIG_ENDIAN = true;
  private static final boolean UNSIGNED = false;
  private static final boolean SIGNED = true;
  
  
  public static void main(String[] args){
// The jvm should not start the graphics engine because of this variable
    java.lang.System.setProperty("java.awt.headless", "true");
    tone(note(1000,365,1));
  }
    

  public static void tone(byte[] buffer){
    AudioFormat audioFormat=new AudioFormat(SAMPLE_RATE, BITS_PER_SAMPLE, MONO, SIGNED, LITTLE_ENDIAN);

    try{
// THE MESSAGE ERROR APPEARS AFTER INITIATE THIS CLASS
        SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
        sourceDataLine.open(audioFormat);
        sourceDataLine.start();
        sourceDataLine.write(buffer,0,buffer.length);
        
        sourceDataLine.drain();
        sourceDataLine.stop();
    }catch(LineUnavailableException ex){
      System.out.println("LineUnavailableException: "+ex.getMessage());
    }catch(IllegalArgumentException ex){
      System.out.println("IllegalArgumentException: "+ex.getMessage());
    }
  }
  
  public static byte[] note(double hertz, double duration, double volume){
    int n = (int) (SAMPLE_RATE * duration / 1000d);
    double[] angle = new double[n+1];
    byte[] buffer=new byte[angle.length*2];
    for (int i = 0; i <= n; i++){
      angle[i] = volume * Math.sin(2 * Math.PI * i * hertz / SAMPLE_RATE);
      if (angle[i] < -1.0) angle[i] = -1.0;
      if (angle[i] > +1.0) angle[i] = +1.0;
      // convert to bytes
      short s = (short) (MAX_16_BIT * angle[i]);
      buffer[i*2] = (byte) s;
      buffer[i*2+1] = (byte) (s >> 8); // little endian
    }
    return buffer;
  }
    
    
    
  
  
}