1
votes

i have this code here :

 NAudio.Wave.WaveIn sourceStream = null;
    NAudio.Wave.DirectSoundOut waveOut = null;
    NAudio.Wave.WaveFileWriter waveWriter = null;
        private void button3_Click(object sender, RoutedEventArgs e) // Start
    {
        ShowImage();

        sourceStream = new NAudio.Wave.WaveIn();
        sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, 2);

        NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);

        waveOut = new NAudio.Wave.DirectSoundOut();
        waveOut.Init(waveIn);

        sourceStream.StartRecording();
    }

    private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
    {
        if (waveWriter == null) return;

        waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
        waveWriter.Flush();
    }

    private void btnStop_Click(object sender, RoutedEventArgs e)
    {
        if (waveOut != null)
        {
            waveOut.Stop();
            waveOut.Dispose();
            waveOut = null;
        }
        if (sourceStream != null)
        {
            sourceStream.StopRecording();
            sourceStream.Dispose();
            sourceStream = null;
        }
        if (waveWriter != null)
        {
            waveWriter.Dispose();
            waveWriter = null;
        }

        sourceStream = new NAudio.Wave.WaveIn();
        sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, 2);
        sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
        waveWriter = new NAudio.Wave.WaveFileWriter(@"../../StoryImages/", sourceStream.WaveFormat);

        sourceStream.StopRecording();
    }

Am i doing it correctly? I seen tutorials and tried but i am really weak in programming , theres a problem with the Buffer that seems to crash my whole application. It always says buffer is full. Theres a problem with

WriteData(e.Buffer , 0,e.BytesRecorded);

i am using NAudio to do this in WPF , am using visual studio 2010.

2

2 Answers

0
votes

Maybe I missunderstand you, but the code you posted seems a little bit unstructured. At the moment you start your recording with button3_Click, your WaveWriter is still null. Why dont you create an instance of this writer also in button3_click ?

In total I would recommend to sort your object creation and disposing. -> Start method should contain all object creation, as well as adding the event handler with "+=". The stop button handler should contain all closing of the stream, and freeing the ressources.

0
votes

I think the probleme here is that the buffer is never emptied. You are missing waveOut.Play(); after sourceStream.StartRecording(); to make the buffer properly flow down to the speakers.

Also, you cannot empty the buffer direclty in the sourceStream_DataAvailable callback because it is read only.

If you don`t want audio playback, you will need another sink then DirectSoundOut.