WaveOut Program Crashing

500 Views Asked by At

I'm working on trying to read in raw .wav data and output the data to the speakers, mostly for self-experimentation and teaching. A secondary reason I want the data myself is so I could parse it to try separating pitches perhaps, or building an equalizer or visualization of some sort. So far, I have reading in the data from the file working, verifying the header and whatnot, but then I go to WaveOut and it starts messing up. My code is currently rather spaghetti code, sure, but it's more of an initial test to see if I can or cannot do this. As far as I can tell right now, my program is crashing at waveOutWrite(), and I honestly have no idea why, and I can't find any good examples of how to get WaveOut to work. Here's the relevant bit:

BYTE *sound=(BYTE*)malloc(sizeof(BYTE)*data_size);
readByte(&in,data_size,sound);
cout<<"Loaded. Now playing...\n";
HWAVEOUT waveOut;
WAVEFORMATEX wF={format_tag,channels,sample_rate,byteRate,block_align,bits_per_sample,0};
MMRESULT result;
waveOutOpen(&waveOut,WAVE_MAPPER,&wF,0,0,CALLBACK_NULL);
WAVEHDR hdr;
ZeroMemory(&hdr,sizeof(WAVEHDR));
hdr.dwBufferLength=data_size;
hdr.lpData=(LPSTR)&sound;
waveOutPrepareHeader(waveOut,&hdr,sizeof(WAVEHDR));
waveOutWrite(waveOut,&hdr,sizeof(WAVEHDR));//Crashes here, no crash if commented out. No sound either way.
Sleep(500);
while(waveOutUnprepareHeader(waveOut,&hdr,sizeof(WAVEHDR))==WAVERR_STILLPLAYING)
  Sleep(100);
waveOutClose(waveOut);
1

There are 1 best solutions below

0
On BEST ANSWER

I managed to find what was wrong, for everybody else who comes through. The data I was pulling was just purely the sound data, minus the header. My problem is that it requires the header on top of the sound data, which is another 44 bytes. What I had to do was bump the size of the array by those 44 bytes, slap the header back at the beginning, and change this line:

hdr.lpData=(LPSTR)&sound;

to this:

hdr.lpData=(LPSTR)sound;

Now, thanks to me parsing out the header, I can also correctly choose a bitrate on the fly, calculate the length of the song, and do various other things with it, too.