Sine Wave Sound Generator in Java

后端 未结 7 1987
时光说笑
时光说笑 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:10

    If you want some easy code to get you started, this should help

    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    
    public class SinSynth {
        //
       protected static final int SAMPLE_RATE = 16 * 1024;
    
    
       public static byte[] createSinWaveBuffer(double freq, int ms) {
           int samples = (int)((ms * SAMPLE_RATE) / 1000);
           byte[] output = new byte[samples];
               //
           double period = (double)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;
       }
    
    
    
       public static void main(String[] args) throws LineUnavailableException {
           final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
           SourceDataLine line = AudioSystem.getSourceDataLine(af);
           line.open(af, SAMPLE_RATE);
           line.start();
    
           boolean forwardNotBack = true;
    
           for(double freq = 400; freq <= 800;)  {
               byte [] toneBuffer = createSinWaveBuffer(freq, 50);
               int count = line.write(toneBuffer, 0, toneBuffer.length);
    
               if(forwardNotBack)  {
                   freq += 20;  
                   forwardNotBack = false;  }
               else  {
                   freq -= 10;
                   forwardNotBack = true;  
           }   }
    
           line.drain();
           line.close();
        }
    
    }
    

提交回复
热议问题