import java.io.*;
import javax.sound.sampled.*;
public class JavaAudioTest
{
public static void main(String args[])
{
for (int i=500; i<1500; i+=100)
{
play(i,1000);
}
}
public static void play(int frequency, int durationMs)
{
play(createData(frequency, durationMs));
}
private static int sampleRate = 16000;
private static byte[] createData(int frequency, int duration)
{
int loudness = 32000;
int sampleCount = sampleRate * duration / 1000;
byte audioData[] = new byte[sampleCount * 2];
for (int i = 0; i < sampleCount; i++)
{
float time = (float)i / sampleRate;
float value = (float)Math.sin(2 * Math.PI * frequency * time);
int sample = (int)(value * loudness);
audioData[i*2+0] = (byte)(sample >> 8);
audioData[i*2+1] = (byte)(sample >> 0);
}
return audioData;
}
private static byte buffer[] = new byte[1<<16];
private static void play(byte data[])
{
AudioFormat audioFormat =
new AudioFormat(sampleRate, 16, 1, true, true);
AudioInputStream audioInputStream = new AudioInputStream(
new ByteArrayInputStream(data), audioFormat,
data.length / audioFormat.getFrameSize());
DataLine.Info dataLineInfo =
new DataLine.Info(SourceDataLine.class, audioFormat);
try
{
SourceDataLine sourceDataLine =
(SourceDataLine)AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
while(true)
{
int read = audioInputStream.read(buffer, 0, buffer.length);
if (read <= 0)
{
break;
}
sourceDataLine.write(buffer, 0, read);
}
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}