我正在使用Naudio在C#中创建自己的软件合成器,并且首先生成一些简单的正弦波,然后播放它们。我想自己做,而不是使用Naudio的内置SignalGenerator
。
将我的自定义对象sine
传递给ISampleProvider
生成正弦波(实现WaveOutEvent.Init
)时,我被抛出了NullReferenceException
。在调用init之前,我已经创建了类SineWave
的实例,但是仍然可以得到NullReferenceException
。
我已经使用WaveOutEvent
命令测试了wo
(SineWave
)和sine
(null
)对象是否都是if
对象,像这样:
if (sineWave != null)
{
Console.WriteLine("sine is not null");
}
if (waveOut != null)
{
Console.WriteLine("wo is not null");
}
这两个语句均通过,并且sine is not null
和wo is not null
均写入控制台。
namespace AddSynth
{
public class SineWave : ISampleProvider
{
public WaveFormat WaveFormat { get; }
int frequency = 440;
int sampleRate = 44100;
double amp = 0.25;
int phase = 0;
public int Read(float[] buffer, int offset, int count)
{
int sampleCount = sampleRate / frequency;
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (float)(amp * Math.Sin(2 * Math.PI * frequency * i + phase));
}
return sampleCount;
}
}
public class Playback
{
static void Main()
{
Playback playBack = new Playback();
playBack.playAudio();
}
public void playAudio()
{
WaveOutEvent waveOut = new WaveOutEvent();
SineWave sineWave = new SineWave();
if (sineWave != null)
{
Console.WriteLine("sine is not null");
}
if (waveOut != null)
{
Console.WriteLine("wo is not null");
}
waveOut.Init(sineWave.ToWaveProvider());
waveOut.Play();
Console.ReadKey();
}
}
}
我希望通过计算机的音频播放正弦波。我希望我已经添加了足够的信息。
编辑:刚刚意识到我可能也应该添加堆栈跟踪,所以它在这里,如果有帮助的话:
at NAudio.Wave.SampleProviders.SampleToWaveProvider..ctor(ISampleProvider source)
at NAudio.Wave.WaveExtensionMethods.ToWaveProvider(ISampleProvider sampleProvider)
at AddSynth.Playback.playAudio() in C:\Users\User1\source\repos\AddSynth\AddSynth\Program.cs:line 44
at AddSynth.Playback.Main() in C:\Users\User1\source\repos\AddSynth\AddSynth\Program.cs:line 29
答案 0 :(得分:0)
正如Nkosi所说,问题在于我从未分配过WaveFormat变量。