我想使用 javax.sound.sampled.SourceDataLine 生成纯正弦波。对于一个恒定的频率,它工作得很好,但是在改变频率时总是有一种咔哒声。我做错了什么,我能做些什么来避免这种情况?
line.start();
final byte[] toneBuffer = new byte[SAMPLE_CHUNK];
while(run) {
createSineWaveBuffer(frequency, toneBuffer);
line.write(toneBuffer, 0, toneBuffer.length);
}
line.drain();
line.close();
在哪里
private double alpha = 0.0;
private static final double step_alpha = (2.0*Math.PI)/SAMPLE_RATE;
private void createSineWaveBuffer(final double freq, final byte[] buffer) {
for(int i = 0; i < buffer.length; ++i) {
buffer[i] = (byte)(Math.sin(freq*alpha)*127.0);
alpha += step_alpha;
if(alpha >= 2.0*Math.PI) {
alpha = 0.0;
}
}
}