Wednesday, May 23, 2012

How to capture sound from microphone and play it on speakers in c#

I have been using NAudio for one of our applications to record sound. Today, I wanted to play back the live recording over the speakers while doing the live record. After few mins of Googling, hammering and fixing. I managed to get something working.


private IWavePlayer waveOut;
private BufferedWaveProvider waveProvider;
private WaveIn m_WaveIn;


private void StartRecording() {
       // Setup Incoming
m_WaveIn = new WaveIn();
m_WaveIn.BufferMilliseconds = 50; // This is very very important.
m_WaveIn.DeviceNumber = set your device here;
m_WaveIn.DataAvailable += WaveIn_DataAvailable;
m_WaveIn.WaveFormat = m_waveFormat;
m_WaveIn.StartRecording();

       // Setup Output


waveOut = new WaveOut();
waveProvider = new BufferedWaveProvider(m_waveFormat);
waveOut.Init(waveProvider);
waveOut.Play();


}


public void WaveIn_DataAvailable(object sender, WaveInEventArgs e) {
    byte[] buffer = e.Buffer;
    waveProvider.AddSamples(buffer, 0, buffer.Length);
}

Thats it. This works like a charm. Hope this will be useful for someone else as well.


1 comment: