Search code examples
c#audionaudiowave

C# NAudio: How to access the samples provided by SignalGenerator in order to save them to WAVE format?


I have the following constructor, which successfully plays pink noise directly to my audio output device:

public WAVEManager(string inputFileName, string outputFileName)
{
        IWavePlayer outputDevice;
        outputDevice = new WaveOutEvent();

        SignalGenerator pinkNoiseGenerator = new SignalGenerator();
        pinkNoiseGenerator.Type = SignalGeneratorType.Pink;
        outputDevice.Init(pinkNoiseGenerator);
        outputDevice.Play();

        // Wait for 10 seconds
        System.Threading.Thread.Sleep(10000);
}

This all works fine. I understand that now if I want to write to a .wav, I have to initialise a WaveFileWriter like so:

WaveFileWriter writer = new WaveFileWriter(outputFileName, pinkNoiseGenerator.WaveFormat);

And then write to the created WAVE file:

writer.WriteData(buffer, 0, numSamples);

The rub being that I have no idea how to populate the buffer directly from pinkNoiseGenerator. I have searched through the documentation and examples and can't find anything to do with this - I imagine it must involve the .Read() method of the SignalGenerator class, but as the generator plays indefinitely, it has no defined length. To me, this means that the buffer can't be populated in the same way it could if we were, say, reading directly from an input WAVE file (as far as I can tell).

Could someone please point me in the right direction?

Thanks.


Solution

  • Here's how you can create a WAV file containing 10 seconds of pink noise:

    var pinkNoiseGenerator = new SignalGenerator();
    pinkNoiseGenerator.Type = SignalGeneratorType.Pink;
    WaveFileWriter.CreateWaveFile16("pinkNoise.wav", pinkNoiseGenerator.Take(TimeSpan.FromSeconds(10)));