March 18th, 2013, 05:21 PM
Problems writting WAV in C#
Hi. I am trying to write a program in C# that generate a WAVE (.wav) file by merging more WAVE files. The problem comes when generating the header of the WAV format.
I am trying to write the header using this: https://ccrma.stanford.edu/courses/4...ts/WaveFormat/
I must create a 16 bit (bit per sample), 8kHz (samplerate) mono (1 channel) wave file, of unknown time length. Most of the code do the job fine, but I have problems with the ChunkSize and Subchunk2Size bytes. I simply do not understand them. In that document it says it's 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size). I just made it the size of the byte array minus 8 (It says: This is the size of the entire file in bytes minus 8 bytes for the two fields not included in this count). The SubChunk2Size, I just don't understand it. It says it must be NumSamples * NumChannels * BitsPerSample/8, it doesn't work anyway.
But also, I don't know if each one of these properties must have their bytes inverted. Because, according to this document: http://ist.uwaterloo.ca/~schepers/formats/WAV.TXT, those two properties have a "lo/hi" format. I don't know if this is true or not, since I haven't seen something like this specified in any document. So, I'm pretty much confused of what should I do with these properties. The current code of my program is the following code:
It should work according to those specifications. The problem is... it doesn't work. The audio files generated with this code seems corrupted with any media player. Why? That's what I'd like to know. There is almost no clear information about how to write WAV headers on the internet, and the information I found is quite unclear in most cases, so I come to you with hopes of clarifying things out. Thanks in advance.
ushort numchannels = 1; // Number of channels
uint samplerate = 8000; //22050
uint numsamples = 0; //It becomes numsamples * (uint)DATA.Length lather
uint bps = 16; //Bits Per Sample
numsamples = numsamples * (uint)DATA.Length; //DATA is the byte array containing the WAVE
wr.Write(DATA.Length - 8); //ChunkSize = FileSize - 8?
wr.Write(Encoding.ASCII.GetBytes("fmt ")); //fmt
wr.Write((uint)samplerate); //Sample rate
wr.Write((uint)(samplerate * numchannels * (bps / 8))); //byte Rate
wr.Write((uint)bps); //Bits Per Sample
wr.Write((uint)numsamples * numchannels * (bps / 8)); //SubChunk2Size
wr.Write(DATA, 0, DATA.Length); //Write DATA buffer
Click Here to Expand Forum to Full Width