當我運行以下代碼時,背景中出現輕微的失真(聽起來像是嗡嗡聲)。由於其微妙的性質,它相信在字節轉換中會出現某種別名。在Java中生成正弦波時的背景噪音
的AudioFormat = PCM_SIGNED 44100.0赫茲,16位,立體聲,4個字節/幀,大端
注:代碼假定(現在),該數據是在大端。
public static void playFreq(AudioFormat audioFormat, double frequency, SourceDataLine sourceDataLine)
{
System.out.println(audioFormat);
double sampleRate = audioFormat.getSampleRate();
int sampleSizeInBytes = audioFormat.getSampleSizeInBits()/8;
int channels = audioFormat.getChannels();
byte audioBuffer[] = new byte[(int)Math.pow(2.0, 19.0) * channels * sampleSizeInBytes];
for (int i = 0; i < audioBuffer.length; i+=sampleSizeInBytes*channels)
{
int wave = (int) (127.0 * Math.sin(2.0 * Math.PI * frequency * i/(sampleRate * sampleSizeInBytes * channels)) );
//wave = (wave > 0 ? 127 : -127);
if (channels == 1)
{
if (sampleSizeInBytes == 1)
{
audioBuffer[i] = (byte) (wave);
}
else if (sampleSizeInBytes == 2)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte)(wave >>> 8);
}
}
else if (channels == 2)
{
if (sampleSizeInBytes == 1)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte) (wave);
}
else if (sampleSizeInBytes == 2)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte)(wave >>> 8);
audioBuffer[i+2] = (byte) (wave);
audioBuffer[i+3] = (byte)(wave >>> 8);
}
}
}
sourceDataLine.write(audioBuffer, 0, audioBuffer.length);
}
是的,這不是問題,因爲緩衝區足以讓聲音通過很多循環。它確實說明了咔嗒聲,但不是持續的嗡嗡聲。 – yxk 2009-04-11 19:55:15
這不是正確的答案 - 代碼清楚地生成大量樣本,並且在每個循環結束時都沒有截斷 – Alnitak 2009-04-11 20:16:13