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

}

最佳答案

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

10-05 21:48