How to create a wave STREAM out of raw audio samples in C#?

refugee picture refugee · May 18, 2010 · Viewed 10.2k times · Source

How to create a wave STREAM out of raw audio samples in C#?

Answer

MusiGenesis picture MusiGenesis · May 18, 2010

Here is a good sample project for reading and writing WAV files in C#:

http://www.codeproject.com/KB/audio-video/Concatenation%5FWave%5FFiles.aspx

Assuming that your "raw audio" is an array of short (2-byte) integers, this is a simple task. The header of a WAV file is 44 bytes (see note), so you write out the header first (using the code in the sample) followed by the data.

Note: not all WAV files are "canonical", which means they don't all have a 44-byte header followed by the data. The WAV format is actually a RIFF format, which means they can contain all kinds of different data and the header isn't necessarily at the beginning. However, none of this matters since you're just writing WAV files.

Update: If the voice recognition program is expecting a stream (as opposed to a file path), it's easy to create a MemoryStream like this:

byte[] bytes = System.IO.File.ReadAllBytes("c:\whatever.wav"); 
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes); 

Or you can avoid File I/O altogether and create your WAV file as an in-memory byte array in the first place, and create the MemoryStream from that.