2

I'm supposed to implement an sinus-generator in java. As an input you give the frequency, amplitute and phase and as an output a .wav file is supposed to be generated.

private static byte[] generateSineWavefreq(int frequencyOfSignal, int seconds) {
    // total samples = (duration in second) * (samples per second)
    byte[] sin = new byte[seconds * sampleRate];
    double samplingInterval = (double) (sampleRate / frequencyOfSignal);
    System.out.println("Sampling Frequency  : "+sampleRate);
    System.out.println("Frequency of Signal : "+frequencyOfSignal);
    System.out.println("Sampling Interval   : "+samplingInterval);
    for (int i = 0; i < sin.length; i++) {
        double angle = (2.0 * Math.PI * i) / samplingInterval;
        sin[i] = (byte) (Math.sin(angle) * 127);
        //System.out.println("" + sin[i]);
    }
    return sin;
}

I generated a sinus like this, but I have huge problems with creating a .wav out of this. I tried some libraries, but especially the header is giving me headache.

Any ideas of how I can implement this easily?

Weedjo
  • 335
  • 1
  • 6
  • 17

1 Answers1

3

"Manually" writing the file is simple. WAV header is not complicated. You know the necessary information (sample rate, duration etc.), then it's just writing them in the file using a BufferedOutputStream, for example.

BufferedOutputStream output = ...
// initialization
...

byte[] toWrite  = new byte[] {'R','I','F','F'};
output.write(toWrite, toWrite.length, 0);
...

But remember some fields are little endian and other big endian. Make some methods like:

byte[] getLittleEndian(int number) {

}

byte[] getBigEndian(int number) {

}
Jean Waghetti
  • 4,711
  • 1
  • 18
  • 28