Reading an Int from a Binary FIle
I have been having a heck of a time reading in an int from a .Wav file.
I've been following the .wav specifications listed Here. I'm trying to
read an int (Subchunk2Size) from the header and then the data into an
array of shorts. I am running into obstacles with both fread() and
ifstream.read(). I will list my problems with both reading technique
problems, but really only need an answer to one.
fread()
sprintf(filename, "C:\\Users\\MacbookWin7\\wavs\\%s.wav", word);
FILE * infile = fopen(filename, "rb");
if (infile != NULL)
{
int f = ferror(infile);
int d = fseek(infile, 40, SEEK_SET);
int * subChunk2Size = new int[1];
int i = fread(subChunk2Size, sizeof(int), 1, infile);
int g = ferror(infile);
The Problem: fread does not read in anything, i is always initialized to 0.
I have tried many different combinations of declaring subChunk2Size,
trying to declare a pointer, an array - both with single and multiple
elements, declaring a nullptr, and declaring an int and passing in its
reference.
ifstream.read()
sprintf(filename, "C:\\Users\\MacbookWin7\\wavs\\%s.wav", word);
ifstream sampleStream(filename,ios::binary);
char * samplesStr;
if (sampleStream.is_open())
{
sampleStream.seekg(40);
char * subChunk2SizeStr = new char[4];
sampleStream.read(subChunk2SizeStr, 4);
int subChunk2Size = 0;
for (int i = 3; i >= 0; i--)
{
subChunk2Size = (subChunk2Size << 8) + subChunk2SizeStr[i];
}
int numBytes = subChunk2Size + *nsamples * 2;
char * samplesStr = new char[numBytes];
sampleStream.read(samplesStr, numBytes);
sampleStream.close();
short * samples = new short[numBytes / 2];
for (int i = 0; i < numBytes / 2; i++)
{
int b = i * 2;
samples[i] = samplesStr[b+1];
samples[i] = (samples[i] << 8) + samplesStr[b];
}
The Problem: My first reads and bit shifts turn out the correct answer of
around 22,000, but I am unable to read in the shorts with the second loop.
I would like to thank anybody for giving my problem some consideration.
No comments:
Post a Comment