Java中的正弦波声音发生器 [英] Sine Wave Sound Generator in Java

查看:27
本文介绍了Java中的正弦波声音发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the simplest way to generate a sine wave sound at any frequency in Java? A sample size more than 2 bytes would help, but it doesn't really matter.

推荐答案

参见 Beeper一个独立的例子.

See Beeper for a self-contained example.

也许更简单的事情?

如链接答案顶部所示的那 51 行代码片段(在下面重复 - 为单行和行内注释隔开),就像生成一个音调一样简单(好吧,你可以去掉5+ 线用于谐波).

That 51 lines of snippet (repeated below - spaced out for single line & in-line comments) as shown at the top of the linked answer, is about as simple as generating a tone gets (OK, you can take out 5+ lines for the harmonic).

人们似乎认为它应该是工具包中内置的一种方法来产生纯音.不是,需要一点点计算才能制作.

People seem to assume it should be a method built into the toolkit to produce a pure tone. It is not, and takes a little calculating to make one.

/** 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();
    }
}

这篇关于Java中的正弦波声音发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆