I am creating my own software synthesizer in C#, using Naudio, and am starting off by generating some simple sine waves and then playing them. I would like to do this myself, rather than using Naudio's inbuilt SignalGenerator
.
When passing my custom object sine
to generate a sine wave (that implements ISampleProvider
) to WaveOutEvent.Init
, I get thrown a NullReferenceException
. I have created an instance of the class SineWave
prior to calling init, but I still get that NullReferenceException
.
I have tested whether both my WaveOutEvent
(wo
) and SineWave
(sine
) objects are null
, with if
commands, like this:
if (sineWave != null)
{
Console.WriteLine("sine is not null");
}
if (waveOut != null)
{
Console.WriteLine("wo is not null");
}
Both of these statements pass, and both sine is not null
and wo is not null
are written to the console.
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();
}
}
}
I expect for a sine wave to be played through my computer's audio. I hope I've added enough info.
EDIT: Just realised that I probably should have added the stack trace as well, so here it is, if it helps:
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
As Nkosi said, the problem was that I never assigned the WaveFormat variable.