c#生成随机粉红噪声
时间: 2024-02-03 13:01:52 浏览: 208
以下是使用C#生成随机粉红噪声的示例代码:
```csharp
using System;
using System.Media;
public class PinkNoiseGenerator
{
private Random random;
private double[] buffer;
private double b0, b1, b2, b3, b4, b5, b6;
public PinkNoiseGenerator()
{
random = new Random();
buffer = new double[7];
}
public double GenerateSample()
{
double white = random.NextDouble() * 2 - 1;
b0 = 0.99886 * b0 + white * 0.0555179;
b1 = 0.99332 * b1 + white * 0.0750759;
b2 = 0.96900 * b2 + white * 0.1538520;
b3 = 0.86650 * b3 + white * 0.3104856;
b4 = 0.55000 * b4 + white * 0.5329522;
b5 = -0.7616 * b5 - white * 0.0168980;
double pink = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362;
b6 = white * 0.115926;
return pink;
}
}
public class Program
{
public static void Main()
{
PinkNoiseGenerator generator = new PinkNoiseGenerator();
SoundPlayer player = new SoundPlayer();
int sampleRate = 44100;
int duration = 5; // 5 seconds
byte[] audioData = new byte[sampleRate * duration * 2]; // 16-bit audio
for (int i = 0; i < audioData.Length / 2; i++)
{
short sampleValue = (short)(generator.GenerateSample() * short.MaxValue);
byte[] sampleBytes = BitConverter.GetBytes(sampleValue);
audioData[i * 2] = sampleBytes[0];
audioData[i * 2 + 1] = sampleBytes[1];
}
player.Stream = new System.IO.MemoryStream(audioData);
player.Play();
}
}
```
这段代码使用了一个粉红噪声生成器类`PinkNoiseGenerator`来生成粉红噪声样本。然后,将生成的样本转换为16位音频数据,并使用`SoundPlayer`类播放生成的粉红噪声。
请注意,这段代码使用了`System.Media`命名空间,因此需要在项目中添加对`System.Media`的引用。
阅读全文