1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <vector>
#include <fstream>
using std::vector; using std::ifstream;
struct wavFile
{
unsigned char s1[5]; // "RIFF"
unsigned long size;
unsigned char s2[5]; // "WAVE"
unsigned char s3[5]; // "fmt "
unsigned long FormatLength;
unsigned short FormatTag;
unsigned short nChannels;
unsigned long nSamplesPerSec;
unsigned long nAvgBytesPerSec;
unsigned short nBlockAlign;
unsigned short BitsPerSample;
unsigned char s4[5]; // "data"
unsigned long data_size;
// EDIT: This was my original problem
// vector<char> cSamp;
// vector<short> sSamp;
// vector<int> iSamp;
// This was my solution: (convert everything to 32 bits on the way in)
vector<int> iSamp;
};
void LoadWavFile(char *fname, wavFile &DATA)
{
//This was another problem:
//ifstream fin(fname);
//Solution:
ifstream fin(fname, std::ifstream::binary);
fin.read( (char*) DATA.s1 , 4*sizeof(unsigned char) ); DATA.s1[4] = '\0';
fin.read( (char*)&DATA.size , sizeof(DATA.size) );
fin.read( (char*) DATA.s2 , 4*sizeof(unsigned char) ); DATA.s2[4] = '\0';
fin.read( (char*) DATA.s3 , 4*sizeof(unsigned char) ); DATA.s3[4] = '\0';
fin.read( (char*)&DATA.FormatLength , sizeof(DATA.FormatLength) );
fin.read( (char*)&DATA.FormatTag , sizeof(DATA.FormatTag) );
fin.read( (char*)&DATA.nChannels , sizeof(DATA.nChannels) );
fin.read( (char*)&DATA.nSamplesPerSec , sizeof(DATA.nSamplesPerSec) );
fin.read( (char*)&DATA.nAvgBytesPerSec, sizeof(DATA.nAvgBytesPerSec));
fin.read( (char*)&DATA.nBlockAlign , sizeof(DATA.nBlockAlign) );
fin.read( (char*)&DATA.BitsPerSample , sizeof(DATA.BitsPerSample) );
fin.read( (char*) DATA.s4 , 4*sizeof(unsigned char) ); DATA.s4[4] = '\0';
fin.read( (char*)&DATA.data_size , sizeof(DATA.data_size) );
switch (DATA.BitsPerSample)
{
case 8:
DATA.cSamp.reserve(DATA.data_size);
char temp;
unsigned long nb_samples = DATA.data_size / sizeof(temp);
for (unsigned long i=0; i<nb_samples; i++)
{
fin.read((char*)&temp, sizeof(temp));
DATA.cSamp.push_back(temp); //I should have used iSamp here
}
break;
case 16:
DATA.sSamp.reserve(DATA.data_size);
short temp;
unsigned long nb_samples = DATA.data_size / sizeof(temp);
for (unsigned long i=0; i<nb_samples; i++)
{
fin.read((char*)&temp, sizeof(temp));
DATA.sSamp.push_back(temp); //I should have used iSamp here
}
break;
case 32:
DATA.iSamp.reserve(DATA.data_size);
int temp;
unsigned long nb_samples = DATA.data_size / sizeof(temp);
for (unsigned long i=0; i<nb_samples; i++)
{
fin.read((char*)&temp, sizeof(temp));
DATA.iSamp.push_back(temp);
}
break;
}
}
int main()
{
wavFile Buffer0;
LoadWavFile("./voiceCreator/wav0.wav", Buffer0);
//Do stuff with buffer
}
|