C++ reading 16bit Wav file

前端 未结 5 1032
感情败类
感情败类 2021-01-07 05:11

I\'m having trouble reading in a 16bit .wav file. I have read in the header information, however, the conversion does not seem to work.

For example, in Matlab if I r

5条回答
  •  不要未来只要你来
    2021-01-07 05:35

    There are a few problems here:

    • 8 bit wavs are unsigned, but 16 bit wavs are signed. Therefore, the subtraction step given in the answers by Carl and Jay are unnecessary. I presume they just copied from your code, but they are wrong.
    • 16 bit waves have a range from -32,768 to 32,767, not from -256 to 255, making the multiplication you are using incorrect anyway.
    • 16-bit wavs are 2 bytes, thus you must read two bytes to make one sample, not one. You appear to be reading one character at a time. When you read the bytes, you may have to swap them if your native endianness is not little-endian.

    Assuming a little-endian architecture, your code would look more like this (very close to Carl's answer):

    for (int i = 0; i < size; i += 2)
    {
        int c = (data[i + 1] << 8) | data[i];
        double t = c/32768.0;
        rawSignal.push_back(t);
    }
    

    for a big-endian architecture:

    for (int i = 0; i < size; i += 2)
    {
        int c = (data[i] << 8) | data[i+1];
        double t = c/32768.0;
        rawSignal.push_back(t);
    }
    

    That code is untested, so please LMK if it doesn't work.

提交回复
热议问题