Question

I have been struggling days to properly write the data from an audio buffer to a wave file... I have checked generating a sine wave to the wav file, and it works fine. However writing audio buffer data as Int16 to the wav file results in a constant high white noise. i.e. I can barely hear what I played on the instrument (heavily distorted). Audio buffers are taken from ASIO input buffer using the ASIO SDK from steinberg.

This is the function called when each input buffer is populated. Buffer size is 176 samples. I copy the buffer's value from the address returned from it into a pointer called sound. (This works without noise if i put in a sine wave in here without the buffers)

 void bufferSwitch(long index, ASIOBool processNow)   {


   for(int i=0; i<176; i++) {

   memcpy(sound+soundcount,(Int16 *)bi.buffers[index]+i,2);

   soundcount++;

   }

 } 

The wave header is as follows. The header works and plays fine with a sine wave.

strcpy(WAV->ChunkID, "RIFF");
WAV->ChunkSize = (uint32_t)size - 8;
strcpy(WAV->RIFFType, "WAVE");

strcpy(Format->ChunkID, "fmt ");
Format->ChunkSize = 16;
Format->CompressionCode = 1;
Format->Channels = 1;
Format->SampleRate = (uint32_t)44100;
Format->SigBitsPerSamp = 16;
Format->BlockAlign = 2;
Format->AvgBytesPerSec = Format->BlockAlign * 44100;

strcpy(Datal->ChunkID, "data");
Datal->ChunkSize = 3 * 44100 *2;
sound = (Int16 *)(Datal + 1);

The sample type as specified by GetSampleType() from ASIO SDK is 16 i.e. Int 16 LSB. Therefore I used Int16 as the data type for the samples. When the samples are printed using a printf it gives low values between +25 and -25 in each sample (it is low since the values lie between +32767 and -32767 in a 16 bit pcm wav). I don't understand how the high noise is generated. However when analyzed through Audacity, the file has a lot of peaks as expected by the noise. Where am I going wrong and is endianess a issue in this?

EDIT (Solved):

Okay I found the error. As I was saying the input and the buffers were flawless. It was an error in writing the data. I used fwrite earlier to write the bufferss which caused garbage bytes to be added to the file. Now I used the ofstream to write the data and it works like a magic. I think there is something wrong with fwrite method.

Was it helpful?

Solution

I inspected the wav file from a hex editor and found some interesting developments. The data is flawlessly written upto about 380 bytes. Then large garbage integers are written for about another 400 bytes. However when i print the values from the pointer by looping it, the values are accurate.

The solution was to use ofstream to write into the file instead of using fwrite.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top