Search code examples
c++type-conversionbinaryfilespcm

How to read raw PCM data from file and convert to float?


I read a binary file of raw PCM data but cannot convert it to floats correctly. I am reading a raw pcm file that audacity recognizes as 16 bit unsigned. I am using the following code:

fseek(stream, 0, SEEK_END);
size = ftell(stream);
fseek(stream, 0, SEEK_SET);
uint8_t * buf = (uint8_t *)malloc(size);
float * f = (float *)malloc(size * sizeof(float) / 2);

//read buffer
fread(buf, sizeof(uint8_t), size, stream);

//convert to float:
for(int j=0;j<size;j+=2){
  int16_t temp1 = buf[j] | buf[j+1] << 8;
  f[j/2]=(float)temp1/(float)32767.0;
  if( f[j/2] > 1 ) 
    f[j/2] = 1;
  if( f[j/2] < -1 ) 
    f[j/2] = -1;
}

What am I doing wrong here?


Solution

  • j increments by 2 so you are only filling in every other value of f[].

    Instead, assign f[j>>1]

    Hopefully you allocated f to hold at least j/2 floats.