Search code examples
c#signal-processingnaudio

SignalGenerator class at naudio library - duration time play


I use naudio for generating a tone in a specified frequency like that:

private void gen_Sinus(double frequency)
    {
        WaveOut _myWaveOut = new WaveOut();

        SignalGenerator mySinus = new SignalGenerator(44100, 1);//using NAudio.Wave.SampleProviders; 
        mySinus.Frequency = frequency;
        mySinus.Type = SignalGeneratorType.Sin;
        _myWaveOut.Init(mySinus);
        _myWaveOut.Play();
    }

I want that when clicking a button it will play that tone for a specific time that will be passed to this method. Let's call it for example:

double toneDuration

I prefer to prevent some sleep methods because it has to be as accurate as possible.


Solution

  • You can use OffsetSampleProvider to do this, and set the Take duration:

    var trimmed = new OffsetSampleProvider(signalGenerator);
    trimmed.Take = TimeSpan.FromSeconds(10);
    waveOut.Init(trimmed);
    waveOut.Play();