Hello,
I've been researching some audio and trying a few implementations. I've hit a wall I can't solve, and wanted to see if anybody had any ideas. I'm generating samples off a sine wave, formatting the wave file, and everything is going great. When I actually write the information to a file, it seems that every so often the information gets corrupted. "Every so often" meaning consistently and in the same places every time.
I was able to narrow it down to the fwrite calls by checking every short that was generated, and each that was written. When it's writing, all of the values are correct. When I open the file and read it to double check, there are tons of samples that have different values than it calculated. Here's a picture:
The sine wave is in there, it's just got what looks like random noise. The audio does play, it just sounds like it looks like it sounds. Here is the relevant code:
Code:
typedef struct
{
CHUNK_HEADER header;
//uint8_t* byteArray; // for 8 bit sound
short* shortArray; // for 16 bit sound
} DATA_CHUNK;
format.header.dwChunkSize = 16;
format.wFormatTag = 1;
format.wChannels = 1;
format.dwSamplesPerSec = 44100;
format.dwBitsPerSample = 16;
format.wBlockAlign = format.wChannels * (format.dwBitsPerSample / 8);
format.dwAvgBytesPerSec = format.wBlockAlign * format.dwSamplesPerSec;
data.shortArray = (short*)malloc((seconds * format.dwSamplesPerSec) * sizeof(short));
memset(data.shortArray, '0', seconds * format.dwSamplesPerSec * sizeof(short));
data.header.dwChunkSize = seconds * format.dwAvgBytesPerSec;
populate_samples(data.shortArray, &format, seconds, check_bytes);
main_header.dwFileLength = 4 + 16 + (format.dwAvgBytesPerSec * seconds);
FILE *wav_file = fopen(FILENAME, "w+");
FILE *check_file;
fwrite(&main_header, 1, sizeof(main_header), wav_file);
fwrite(&format, 1, sizeof(format), wav_file);
fwrite(&data.header, 1, 8, wav_file);
fwrite(data.shortArray, 2, (format.dwSamplesPerSec * seconds), wav_file);
fclose(wav_file);
I'm stumped. Any ideas?