我正在尝试实时生成一组同时音调。但是程序产生的所有声音都是“模糊的”,或者有“静态的”,甚至听起来像背景中的“尖叫”。这在低音调的声音中尤其明显。这是代码:
static final long bufferLength = 44100;
static final AudioFormat af = new AudioFormat(bufferLength, 8, 1, true, false);
static boolean go = true; //to be changed somewhere else
static void startSound(double[] hertz) {
if (hertz.length == 0) {return;}
try {
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open();
sdl.start();
int i = 0;
//iterate as long as the sound must play
do {
//create a new buffer
double[] buf = new double[128]; //arbitrary number
final int startI = i;
//iterate through each of the tones
for (int k = 0; k < hertz.length; k++) {
i = startI;
//iterate through each of the samples for this buffer
for (int j = 0; j < buf.length; j++) {
double x = (double)i/bufferLength*hertz[k]*2*Math.PI;
double wave1 = Math.sin(x);
//decrease volume with increasing pitch
double volume = Math.min(Math.max(300 - hertz[k], 50d), 126d);
buf[j] += wave1*volume;
i++;
if (i == 9999999) { //prevent i from getting too big
i = 0;
}
}
}
final byte[] finalBuffer = new byte[buf.length];
//copy the double buffer into byte buffer
for (int j = 0; j < buf.length; j++) {
//divide by hertz.length to prevent simultaneous sounds
// from becoming too loud
finalBuffer[j] = (byte)(buf[j]/hertz.length);
}
//play the sound
sdl.write(finalBuffer, 0, finalBuffer.length);
} while (go);
sdl.flush();
sdl.stop();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
//play some deep example tones
startSound(new double[]{65.4064, 58.2705, 48.9995});
我试过记录这个程序输出的声音,波浪看起来确实有点锯齿状。但是当我直接从程序中打印出生成的波时,它们看起来非常平滑。我产生的声音似乎与扬声器发出的声音不匹配。谁能抓住我做错了什么?