What\'s the simplest way to generate a sine wave sound at any frequency in Java? A sample size more than 2 bytes would help, but it doesn\'t really matter.
The createSinWaveBuffer() method in these answers does not produce good waveform data for playing continuously. Need to have the last byte be near zero to have a complete waveform. Better example -
protected static final float SAMPLE_RATE = 16 * 1024;
public static byte[] createSinWaveBuffer(double freq) {
double waveLen = 1.0/freq;
int samples = (int) Math.round(waveLen * 5 * SAMPLE_RATE);
byte[] output = new byte[samples];
double period = SAMPLE_RATE / freq;
for (int i = 0; i < output.length; i++) {
double angle = 2.0 * Math.PI * i / period;
output[i] = (byte)(Math.sin(angle) * 127f); }
return output;
}