[英]Creating sine or square wave in C#
如何生成給定頻率的音頻正弦波或方波?
我希望這樣做是為了校准設備,那么這些波的精確度如何?
您可以使用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)
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);
}
使用Math.NET 數字
https://numerics.mathdotnet.com/Generate.html
正弦
生成給定長度的正弦波陣列。 這等效於將縮放三角正弦函數應用於幅度為 2π 的周期性鋸齒波。
s(x)=A⋅sin(2πνx+θ)
Generate.Sinusoidal(length,samplingRate,frequency,amplitude,mean,phase,delay)
例如
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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.