tags:

views:

343

answers:

2

If you have a lisp, please dont try and say my title.

But yes, whats the easiest way to generate simple, or Bonus for more complex sawtooth and other waves.

kthxbye

+2  A: 

In my experience the .wav file format (the Wikipedia entry lists other documents giving the file format; use whichever you find best) is the simplest widely-used one. It's pretty easy to write uncompressed PCM.

For things like sine waves and sawtooths, I'd split the task into sampling and file production. So you might have an interface such as:

public interface IWave
{       
    double Sample(double time);
}

where Sample will be given a time greater than 0 (but possibly greater than 1) and should return a value between -1 and 1. (You could use a delegate for this instead.) Then write a file generator to create a wav file based on the sample duration (e.g. "100000 waves") and sample frequency (e.g. 50000 Hz).

Then it's just a case of implementing IWave appropriately - e.g. a version which returns sin(time / (2 * pi)) for a simple sine wave, or (time % 1.0) * 2 - 1 for a sawtooth. For bonus amusement, you could write composition functions to speed up or slow down the wave, amplify it, combine other waves etc. The file generator wouldn't need to know any of that, of course. It would just need to take a single IWave and sample it the appropriate number of times, scaling the [-1, 1] range to [0, 255] appropriately.

Jon Skeet
+1  A: 

Just to elaborate on what Jon already said - all you do is create an 8-bit (i.e. byte[1024]) or 16-bit buffer and fill it out (i.e. for a square wave it's [255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0]).

Paul Betts