Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sine wave alternates distortion in Java

I'm trying to generate sine wave and add it to byte array. I searched and found. However, I always get distorted waveform like an attachment.

Please give me your opinion why it happens. Thanks.

My code is here

private byte[] getData(int freq) {   // taking pitch data
    double pha = Math.PI/2;          // defining phase
    final int LENGTH = 44100 * 10;   // defining length of sine wave, byte array
    final byte[] arr = new byte[LENGTH];
    for(int i = 0; i < arr.length; i++) {
        double angle = (2.0 * Math.PI * i*freq+pha) / (44100); 
        arr[i] = (byte) (Math.cos(angle) *127* 0.3);    // 0.3 is amplitude scale        
    }
    return arr;
}

Distort waveform example pic

enter image description here

like image 732
Bilge Mirac Atici Avatar asked Mar 12 '26 09:03

Bilge Mirac Atici


1 Answers

The code looks fine. I suspect it's the visualiser interpreting the two's complement signed values as unsigned (-1 becoming 255, -2 becoming 254 and so on).

I write to a wav file and plot it with SonicVisualiser

According to WAVE PCM soundfile format:

8-bit samples are stored as unsigned bytes, ranging from 0 to 255. 16-bit samples are stored as 2's-complement signed integers, ranging from -32768 to 32767.

It looks like you either need to shift your sine wave up by 128 (so that it fits fully within the 0-255 range), or move to using 16-bit samples.

like image 56
NPE Avatar answered Mar 14 '26 22:03

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!