我直接从http://mark-dot-net.blogspot.com/2009/10/playback-of-sine-wave-in-naudio.html使用带有 SineWaveProvider32 代码的 naudio来生成正弦波音调。SineWaveProvider32 类中的相关代码:
public override int Read(float[] buffer, int offset, int sampleCount)
{
int sampleRate = WaveFormat.SampleRate;
for (int n = 0; n < sampleCount; n++)
{
buffer[n + offset] =
(float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate));
sample++;
if (sample >= sampleRate) sample = 0;
}
return sampleCount;
}
我每秒钟都有点击/节拍,所以我改变了
if (sample >= sampleRate) sample = 0;
至
if (sample >= (int)(sampleRate / Frequency)) sample = 0;
这固定了每秒的点击次数(因此“样本”始终与过零相关,而不是采样率)。
但是,每当我设置 Amplitude 变量时,都会点击一下。我尝试仅在缓冲区 [] 处于过零时设置它,认为幅度的突然跳跃可能会导致问题。那并没有解决问题。我将振幅设置为 0.25 和 0.0 之间的值
我尝试按照NAudio change volume in runtime中的建议调整延迟和缓冲区数量,但这也没有效果。
我改变振幅的代码:
public async void play(int durationMS, float amplitude = .25f)
{
PitchPlayer pPlayer = new PitchPlayer(this.frequency, amplitude);
pPlayer.play();
await Task.Delay(durationMS/2);
pPlayer.provider.Amplitude = .15f;
await Task.Delay(durationMS /2);
pPlayer.stop();
}