views:

3627

answers:

3

How do a I generate an audio sine or square wave of a given frequency.

I am hoping to do this to calibrate equipment, so how precise would these waves be?

+8  A: 

You can use NAudio and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a WAV file. If you used 32 bit floating point samples you could write the values directly out of the sin function without having to scale as it already goes between -1 and 1.

As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sin wave will likely have a few very quiet artifacts at other frequencies. If its accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your soundcard. Having said that, I would imagine that the accuracy would be good enough for most uses.

Update - here's some example code that makes a 1kHz sample rate at 8kHz sample rate and with 16 bit samples (i.e. not floating point):

int sampleRate = 8000;
short[] buffer = new short[8000];
double amplitude = 0.25 * short.MaxValue;
double frequency = 1000;
for (int n = 0; n < buffer.Length; n++)
{
    buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate));
}
Mark Heath
here is no such thing as a true square wave, and even the sin wave: Very correct, I actually meant frequency, thanks
johnc
A: 

This will depend far more on your hardware rather then your software. Are you using a sound card to generate audio, or some other board to generate an electronic signal?

Jim C
+1  A: 

Here is some code for creating a sine wave correctly

d= 40000; //fundamental freq of sine/sample rate

for (int n = 0; n < d; n++)
{
    buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * ) / d);
}
kamaerugag