Joshua Coffey
Joshua Coffey

Reputation: 330

Record input from NAudio WaveIn, and output to NAudio WaveOut

I want to be able to get input from a microphone device via NAudio.WaveIn, and then output that exact input to an output device via NAudio.WaveOut.

How would I do this?

Upvotes: 10

Views: 22357

Answers (2)

Mark Heath
Mark Heath

Reputation: 49482

The best way would be to use a BufferedWaveProvider as the input to WaveOut. Then in the DataAvailable callback of WaveIn, supply the data recorded to the BufferedWaveProvider

void DataAvailable(object sender, WaveInEventArgs args)
{
    bufferedWaveProvider.AddSamples(args.Buffer, 0, args.BytesRecorded);
}

You need to be aware that the default buffer sizes will result in a noticeable delay, so if you were hoping for low latency you might need to experiment a bit with buffer sizes to see how low you can get it.

Upvotes: 4

Justin Geeslin
Justin Geeslin

Reputation: 3411

Here is the code that worked for me:

using NAudio.Wave;
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form4 : Form
    {
        private BufferedWaveProvider bwp;
        WaveIn wi;
        WaveOut wo;

        public Form4()
        {
            InitializeComponent();
            wo = new WaveOut();
            wi = new WaveIn();
            wi.DataAvailable += new EventHandler<WaveInEventArgs>(wi_DataAvailable);

            bwp = new BufferedWaveProvider(wi.WaveFormat);
            bwp.DiscardOnBufferOverflow = true;

            wo.Init(bwp);
            wi.StartRecording();
            wo.Play();
        }

        void wi_DataAvailable(object sender, WaveInEventArgs e)
        {
            bwp.AddSamples(e.Buffer, 0, e.BytesRecorded);
        }
    }
}

Upvotes: 14

Related Questions