This project has moved. For the latest updates, please go here.

AudioCapture is not working as expected

Dec 29, 2010 at 12:36 AM

In my Microsoft Surface application I'd like to use voice capture. So I followed the tutorial metioned here (http://opensebj.blogspot.com/2009/04/naudio-tutorial-5-recording-audio.html) and modified the NAudio.dll to be able to execute the following code:

 

 class AudioRecording
    {
        private WaveMixerStream32 mixer;
       
        public AudioRecording()
        {
            mixer = new WaveMixerStream32();
            mixer.AutoStop = false;
         
        }

        public void start()
        {
            Console.WriteLine("Start recording"); 
            mixer.StreamMixToDisk("Test.wav");
            mixer.StartStreamingToDisk();
        }

        public void stop()
        {
            Console.WriteLine("Stop recording");
            mixer.StopStreamingToDisk();
        }
    }

But this doesn't really capture the sound. I just create a file of 58 bytes, that is empty. What Am I doing wrong?

Editor
Dec 29, 2010 at 9:50 AM

That tutorial is showing you how to record audio that has been mixed by NAudio. 

If you haven't mixed any NAudio through then using the bulk of that tutorial wont help.

You just need the bit under the "recording from the sound card":

Recoding from the Sound Card

This is remarkably simple to achieve in NAudio, short of having a big red button which we push before it leaves the factory. First step is to setup.. ah forget the steps here is the code:

// WaveIn Streams for recording
WaveIn waveInStream;
WaveFileWriter writer;

waveInStream = new WaveIn(44100,2);
writer = new WaveFileWriter(outputFilename, waveInStream.WaveFormat);

waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
waveInStream.StartRecording();

No joke that's almost it. The only interesting thing here that we need to consider it that we have added an EventHandler that needs to be setup to handle data when it's ready to be handed off to the WaveFileWriter:

void waveInStream_DataAvailable(object sender, WaveInEventArgse)
{
   writer.WriteData(e.Buffer, 0, e.BytesRecorded);
}

Er, thats it to start recording. We can stop the recording as such:

waveInStream.StopRecording();
waveInStream.Dispose();
waveInStream = null;
writer.Close();
writer = null;

Dec 29, 2010 at 10:10 AM

Ah ok, now I understand! It works! Thanks! Now i just have to make the audiowaves visible ;)

Editor
Dec 29, 2010 at 10:43 AM

Check out the demo application packaged with NAudio - it draws the sound as it's being played by using a monitoring stream.

 

Sebastian