'Delay occurred when reading bytes from stdin (Using pipe)

I am writing a C program that take sox's output as input for my program. Generally, my program would read the input from stdin and make some processing afterward. However, when I read byte values from stdin and wrote it back to another file (just to make sure everything is correct), I saw that my result was somehow be delayed (I am not sure about this), comparing to the original one (image is here, the waveform above is the output of sox's command).

Can someone point out for me where do I go wrong please? I have been struggled with this issue for so many hours. I am using Ubuntu 20.04. Thanks! (In case you want my audio file, here it is)

Sox command to generate above waveform

cat arctic_a0010.wav | sox -t wav - -b 16 -e signed -t raw - > mid.raw

Command to generate below waveform

cat arctic_a0010.wav | sox -t wav - -b 16 -e signed -t raw - | ./test

My minimal test.c program

#include <stdio.h>
#include <stdlib.h>

void storeValue(short* arr, short* assignValue, long int startPt, long int numBlock) {
    for (long int i = 0; i < numBlock; i++) {
        arr[startPt + i] = assignValue[i];
    }
}

void readFromStdin(short* arr, long* curSize) {
    long r, n = 0;
    int BUFFER_SIZE = 1024;
    short buffer[BUFFER_SIZE];

    freopen(NULL, "rb", stdin);
    while (1) {
        r = fread(buffer, sizeof(short), BUFFER_SIZE, stdin);
        if (r <= 0) {
            break;
        }
        if (n + r > *curSize) {
            *curSize = n + r;
            arr = (short*)realloc(arr, (*curSize) * sizeof(short));
        }
        storeValue(arr, buffer, n, r);
        n = n + r;
    }
}

int main(int argc, char *argv[])
{
    // Read from stdin
    short* inputArray = (short*)malloc(sizeof(short));
    long InpSize = 1, currentIndex = 0;
    readFromStdin(inputArray, &InpSize);

    // Write to file
    FILE *out = fopen("test.raw", "wb");
    fwrite(inputArray, sizeof(short), InpSize, out);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source