Sine Wave Sound Generator in Java

后端 未结 7 1956
时光说笑
时光说笑 2020-12-05 01:22

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.

相关标签:
7条回答
  • 2020-12-05 02:13

    The createSinWaveBuffer() method in these answers does not produce good waveform data for playing continuously. Need to have the last byte be near zero to have a complete waveform. Better example -

    protected static final float SAMPLE_RATE = 16 * 1024;
    
    public static byte[] createSinWaveBuffer(double freq) {
       double waveLen = 1.0/freq;
       int samples = (int) Math.round(waveLen * 5 * SAMPLE_RATE);
       byte[] output = new byte[samples];
       double period = SAMPLE_RATE / freq;
       for (int i = 0; i < output.length; i++) {
           double angle = 2.0 * Math.PI * i / period;
           output[i] = (byte)(Math.sin(angle) * 127f);  }
    
       return output;
    }
    
    0 讨论(0)
提交回复
热议问题