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

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

问题描述

如何生成给定频率的音频正弦波或方波?

How do 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?

推荐答案

您可以使用 NAudio 并创建一个派生的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.

以下是一些示例代码,它以 8 kHz 采样率和 16 位采样(即非浮点)生成 1 kHz 采样:

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天全站免登陆