建立在C#正弦波或方波 [英] Creating sine or square wave in C#

查看:794
本文介绍了建立在C#正弦波或方波的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何产生特定频率的音频正弦波或方波?

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

我希望能做到这一点来校准设备,所以如何precise将这些波是什么?

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

推荐答案

您可以使用 n音讯并创建派生的WaveStream,输出正弦波或方波可以输出到声卡或写入 WAV 文件。如果您使用的32位浮点样品,你可以直接从sin函数写的值,而无需缩放,因为它已经-1到1之间去。

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 sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses.

下面是一些例子code,使一个1 在8&NBSP kHz的采样; kHz采样率和16位样本(即不浮点):

Here's some example code that makes a 1 kHz sample at a 8 kHz sample rate and with 16 bit samples (that is, 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));
}

这篇关于建立在C#正弦波或方波的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆