SignalGenerator class at naudio library - duration time play

1.3k views Asked by At

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.

2

There are 2 answers

1
Mark Heath On BEST ANSWER

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();
3
jdweng On

Use a timer and a wait handler

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Tick += new EventHandler(timer1_Tick);
        }
        static AutoResetEvent autoEvent = new AutoResetEvent(false);

        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);

            timer1.Interval = 5000;
            timer1.Start()

            _myWaveOut.Play();
            autoEvent.Reset();
            autoEvent.WaitOne();
            _myWaveOut.Stop();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            autoEvent.Set();

        }
    }
}
​