Java中的正弦波声音发生器

Java中以任何频率生成正弦波声音的最简单方法是什么?
样本大小超过2个字节会有所帮助,但这并不重要.

谢谢

解决方法:

有关自包含示例,请参见Beeper.

Perhaps something simpler?

如链接答案顶部所示,51行的片段(重复在下面 – 用于单行和在线注释的间隔)就像生成音调一样简单(好的,你可以取出5行代码)谐波).

人们似乎认为它应该是工具包内置的一种方法,以产生纯净的音调.它不是,并且需要一点计算来制作一个.

/** Generates a tone, and assigns it to the Clip. */
public void generateTone()
    throws LineUnavailableException {
    if ( clip!=null ) {
        clip.stop();
        clip.close();
    } else {
        clip = AudioSystem.getClip();
    }
    boolean addHarmonic = harmonic.isSelected();

    int intSR = ((Integer)sampleRate.getSelectedItem()).intValue();
    int intFPW = framesPerWavelength.getValue();

    float sampleRate = (float)intSR;

    // oddly, the sound does not loop well for less than
    // around 5 or so, wavelengths
    int wavelengths = 20;
    byte[] buf = new byte[2*intFPW*wavelengths];
    AudioFormat af = new AudioFormat(
        sampleRate,
        8,  // sample size in bits
        2,  // channels
        true,  // signed
        false  // bigendian
        );

    int maxVol = 127;
    for(int i=0; i<intFPW*wavelengths; i++){
        double angle = ((float)(i*2)/((float)intFPW))*(Math.PI);
        buf[i*2]=getByteValue(angle);
        if(addHarmonic) {
            buf[(i*2)+1]=getByteValue(2*angle);
        } else {
            buf[(i*2)+1] = buf[i*2];
        }
    }

    try {
        byte[] b = buf;
        AudioInputStream ais = new AudioInputStream(
            new ByteArrayInputStream(b),
            af,
            buf.length/2 );

        clip.open( ais );
    } catch(Exception e) {
        e.printStackTrace();
    }
}
上一篇:232Echarts - 3D 柱状图(Noise modified from marpi's demo)


下一篇:c# – 解决WAV文件中的幅度和频率