java DSP synth奇怪的行为

时间:2013-02-14 10:52:44

标签: java audio signal-processing sound-synthesis

我正在尝试使用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 );
    }

}

1 个答案:

答案 0 :(得分:0)

您没有在缓冲区调用之间保存正弦波的相位。因此,任何相位不连续都会在速率play()被调用时引起嗡嗡声。没有嗡嗡声的频率恰好在您的默认开始阶段结束。