我正在尝试使用 javax.sound.sampled.SourceDataLine 播放保存在字节数组中的信号。我正在尝试开始播放简单的正弦波。对于某些频率(例如 1000Hz、400Hz),它运行良好,但对于其他频率(1001、440),我只会听到几乎无声的嗡嗡声。采样率肯定足够高以防止混叠(16Khz)。有任何想法吗 ?干杯。
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
public class Player
{
private static float SAMPLE_RATE = 16000;
public static void main(String[] args)
{
playSound();
}
private static void playSound()
{
try
{
final AudioFormat audioFormat = new AudioFormat( SAMPLE_RATE, 8, 1, true, true );
SourceDataLine line = AudioSystem.getSourceDataLine( audioFormat );
line.open( audioFormat );
line.start();
/* the last argument here is the frequency in Hz. works well with 1000, but with 1001 I get week and pitchless clicking sound sound*/
byte[] signal = smpSin( 1, 1, 1000 );
play( line, signal );
line.drain();
line.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static byte[] smpSin(double lenInSec, double amp, double signalFreq)
{
int len = (int)(SAMPLE_RATE * lenInSec);
byte[] out = new byte[len];
for (int i = 0; i < out.length; i++)
{
out[i] = (byte)(amp * Math.sin( ((2.0 * Math.PI * signalFreq) * ((double)i)) / SAMPLE_RATE ));
}
return out;
}
private static void play(SourceDataLine line, byte[] array)
{
line.write( array, 0, array.length );
}
}