Bare metal sound
suggest changeYou can also go almost bare-metal when producing sound with Java. This code writes raw samples into the audio line’s buffer. Playback consumes that buffer immediately, so the samples have to be ready in time. hertz must be positive and no greater than the 24 kHz sample rate; otherwise waveHalf is 0 and the loop never advances.
As such this method is unusable for more complicated sound-sampling. For such purposes using specialized tools is the better approach.
The following method generates and directly outputs a rectangle-wave of a given frequency in a given volume for a given duration.
public void rectangleWave(byte volume, int hertz, int msecs) {
final SourceDataLine dataLine;
// 24 kHz x 8bit, single-channel, signed little endian AudioFormat
AudioFormat af = new AudioFormat(24_000, 8, 1, true, false);
try {
dataLine = AudioSystem.getSourceDataLine(af);
dataLine.open(af, 10_000); // audio buffer size: 10k samples
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
}
int waveHalf = 24_000 / hertz; // samples for half a period
byte[] buffer = new byte[waveHalf * 20];
int samples = msecs * (24_000 / 1000); // 24k (samples / sec) / 1000 (ms/sec) * time(ms)
dataLine.start(); // starts playback
int sign = 1;
for (int i = 0; i < samples; i += buffer.length) {
for (int j = 0; j < 20; j++) { // generate 10 waves into buffer
sign *= -1;
// fill from the jth wave-half to the j+1th wave-half with volume
Arrays.fill(buffer, waveHalf * j, waveHalf * (j+1), (byte) (volume * sign));
}
dataLine.write(buffer, 0, buffer.length); //
}
dataLine.drain(); // forces buffer drain to hardware
dataLine.stop(); // ends playback
}
Generating other waveforms, such as a sine wave, needs more calculation and often a larger buffer. That code is omitted here.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents