Skip to content

Instantly share code, notes, and snippets.

@jeffypooo
Created January 24, 2017 23:38
Show Gist options
  • Save jeffypooo/db0435d0e9778cddbe422b6d5fe243b0 to your computer and use it in GitHub Desktop.
Save jeffypooo/db0435d0e9778cddbe422b6d5fe243b0 to your computer and use it in GitHub Desktop.
Code to synthesize a 16 bit linear PCM sine wave (tone).
float freq = 440f;
float sRate = 8000f;
int numSamples = (int) (sRate * SINE_WAVE_DUR_SECS);
float[] rawSamples = new float[numSamples];
for (int i = 0; i < numSamples; ++i) {
rawSamples[i] = (float) Math.sin(2.0 * Math.PI * i / (sRate / freq));
}
sineWaveSamples = new byte[numSamples * 2];
int j = 0;
for (float sample : rawSamples) {
final short scaledSample = (short) (sample * 32767);
sineWaveSamples[j++] = (byte) (scaledSample & 0x00ff);
sineWaveSamples[j++] = (byte) ((scaledSample & 0xff00) >>> 8);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment