Is there an library in Java for emitting a certain frequency constantly?

感情迁移 提交于 2019-12-05 10:58:48

I think you'll find that listening to a constant-frequency sound is painful on the ears. However, you could do it something like this, just using standard Java libraries:

AudioFormat format = new AudioFormat(44000f, 16, 1, true, false);
SourceDataLine line = (SourceDataLine)AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, format));

line.open(format);
line.start();

double f = 440; // Hz
double t = 3; // seconds

byte[] buffer = new byte[(int)(format.getSampleRate() * t * 2 + .5)];

f *= Math.PI / format.getSampleRate();

for(int i = 0; i < buffer.length; i += 2) {
    int value = (int)(32767 * Math.sin(i * f));
    buffer[i + 1] = (byte)((value >> 8) & 0xFF);
    buffer[i] = (byte)(value & 0xFF);
}

line.write(buffer, 0, buffer.length);

line.drain();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!