Angelo Gattuso who goes by the name evol76 on the Code Project website has used my C# Wav File Library in a unique way. He’s using images to create wave files. It’s a cool idea, and I like what he did with it.
Check it out here.
I wanted to play around with a wave file in C# that way I could create my own procedure generated waves. So, I started searching around on Google to try and find a C# wave file generator. I couldn’t find anything. I decided to go about making my own and found a lot of information on the wave file format at : ccrma.stanford.edu.
I created a C# library so that anybody else that wants to play with these wave files can. You can get the source code here : Wave Library
This is how you would create a wave file, with white noise, or a constant sound.
1: WaveFile file;
3: private void CreateWaveFile()
5: bool whiteNoise = true;
6: Random rand = new Random();
8: file = new WaveFile(1, 8, 11025);
10: int samples = 11025; //Creates 1 second of audio
12: // Sound Data Array
13: // Size needs to be :
14: // Number Of Channels - 1 for mono
15: // 2 for stereo
16: // Bits Per Sample - How many bits are used to describe each Sample
17: // Samples - How many samples that are provided
19: // Sound Data Size = Number Of Channels * Bits Per Sample * Samples
20: byte data = new byte[file.NumChannels * (file.BitsPerSample / 8) * samples];
22: if (whiteNoise)
24: //Creates White Noise
25: for (int i = 0; i < data.Length; i++)
27: data[i] = (byte)rand.Next(256); //256 is the max size of a byte
32: //Creates a Constant Sound
33: for (int i = 0; i < data.Length; i++)
35: data[i] = (byte)(256 * Math.Sin(i));
39: file.SetData(data, samples);
40: file.WriteFile(@"C:\Test.wav"); //Writes the wave file out to the destination given
You can play with the for loops and create some neat sound effects :
1: float push = 0;
2: //Creates a Constant Sound
3: for (int i = 0; i < data.Length; i++)
5: push += 0.0001f;
6: data[i] = (byte)(256 * Math.Sin(i * push));
That’ll create a nifty little whirl noise with very minimal effort.
The best part is you can then use the DirectSound framework to play your new wave file. This approach could be an easy way to limit your game size and create some neat procedurally generated sounds, all on the fly.
EDIT : The WaveLibrary had an include for LINQ, which it wasn't using. Having that in would throw an error if it were compiled in any Visual Studio below 2008. Thanks to Vulpes for catching that.