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

我希望这样做来校准设备,那么这些波的精确程度如何?

有帮助吗?

解决方案

您可以使用 NAudio 并创建派生的WaveStream,输出您可以输出到声卡的正弦波或方波或写入 WAV 文件。如果使用32位浮点样本,则可以直接从sin函数中写出值,而不必进行缩放,因为它已经介于-1和1之间。

至于准确度,你的意思是恰当的频率,还是恰好正确的波形?没有真正的方波,甚至正弦波也可能在其他频率上有一些非常安静的伪影。如果频率的准确性很重要,那么您依赖于声卡中时钟的稳定性和准确性。话虽如此,我认为准确性对于大多数用途来说已经足够了。

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

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));
}

其他提示

这使您可以给出频率,持续时间和幅度,它是100%.NET CLR代码。没有外部DLL。它的工作原理是创建一个WAV格式的 MemoryStream ,就像在内存中创建一个文件,而不是将其存储到磁盘上。然后它用 System.Media.SoundPlayer 播放 MemoryStream

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
{
    var mStrm = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(mStrm);

    const double TAU = 2 * Math.PI;
    int formatChunkSize = 16;
    int headerSize = 8;
    short formatType = 1;
    short tracks = 1;
    int samplesPerSecond = 44100;
    short bitsPerSample = 16;
    short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
    int bytesPerSecond = samplesPerSecond * frameSize;
    int waveSize = 4;
    int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
    int dataChunkSize = samples * frameSize;
    int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
    // var encoding = new System.Text.UTF8Encoding();
    writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
    writer.Write(fileSize);
    writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
    writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
    writer.Write(formatChunkSize);
    writer.Write(formatType);
    writer.Write(tracks);
    writer.Write(samplesPerSecond);
    writer.Write(bytesPerSecond);
    writer.Write(frameSize);
    writer.Write(bitsPerSample);
    writer.Write(0x61746164); // = encoding.GetBytes("data")
    writer.Write(dataChunkSize);
    {
        double theta = frequency * TAU / (double)samplesPerSecond;
        // 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
        // we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
        double amp = volume >> 2; // so we simply set amp = volume / 2
        for (int step = 0; step < samples; step++)
        {
            short s = (short)(amp * Math.Sin(theta * (double)step));
            writer.Write(s);
        }
    }

    mStrm.Seek(0, SeekOrigin.Begin);
    new System.Media.SoundPlayer(mStrm).Play();
    writer.Close();
    mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)

尝试创建正弦并保存到C#中的wave文件

private void TestSine()
{
    IntPtr format;
    byte[] data;
    GetSineWave(1000, 100, 44100, -1, out format, out data);
    WaveWriter ww = new WaveWriter(File.Create(@"d:\work\sine.wav"),
        AudioCompressionManager.FormatBytes(format));
    ww.WriteData(data);
    ww.Close();
}

private void GetSineWave(double freq, int durationMs, int sampleRate, short decibel, out IntPtr format, out byte[] data)
{
    short max = dB2Short(decibel);//short.MaxValue
    double fs = sampleRate; // sample freq
    int len = sampleRate * durationMs / 1000;
    short[] data16Bit = new short[len];
    for (int i = 0; i < len; i++)
    {
        double t = (double)i / fs; // current time
        data16Bit[i] = (short)(Math.Sin(2 * Math.PI * t * freq) * max);
    }
    IntPtr format1 = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);
    byte[] data1 = new byte[data16Bit.Length * 2];
    Buffer.BlockCopy(data16Bit, 0, data1, 0, data1.Length);
    format = format1;
    data = data1;
}

private static short dB2Short(double dB)
{
    double times = Math.Pow(10, dB / 10);
    return (short)(short.MaxValue * times);
}

(对于其他任何人)使用 Mathnet

https://numerics.mathdotnet.com/generate.html

  

<强>正弦

     

生成给定长度的正弦波阵列。这相当于   将比例三角正弦函数应用于周期性锯齿   振幅2&#960;。

     

S(X)= A&#8901; SIN(2&#960;&#957; X +&#952;)

     

Generate.Sinusoidal(长度,samplingRate,频率,振幅,平均值,相位延迟)

e.g

 Generate.Sinusoidal(15, 1000.0, 100.0, 10.0);

返回数组{0,5.9,9.5,9.5,5.9,0,-5.9,...}

还有

Generate.Square(...

  

创建一个周期性的方波...

不能谈论精确度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top