Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record input from NAudio WaveIn, and output to NAudio WaveOut

Tags:

c#

naudio

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?

like image 262
Joshua Coffey Avatar asked Apr 17 '11 15:04

Joshua Coffey


2 Answers

Here is the code that worked for me:

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 NAudio.Wave;
using NAudio.CoreAudioApi;

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

        }
    }
}
like image 73
Justin Geeslin Avatar answered Nov 07 '22 16:11

Justin Geeslin


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.

like image 41
Mark Heath Avatar answered Nov 07 '22 17:11

Mark Heath