stockDevelopers
stockDevelopers

Reputation: 53

CSCore library using in Windows Forms Application

Here:

C# recording audio from soundcard

is example implementation using CSCore library, but it works only in console application. Is it possible to use this in Windows Forms Application?

Upvotes: 3

Views: 5072

Answers (1)

rene
rene

Reputation: 42453

Yes, it is possible.

You have to split the code over two buttons, say start and stop.
The code before the Console.ReadKey() goes in the Click event of the start button and everything after the Console.ReadKey() goes in the click event of the stop button.

In the console variant all variables are local to the method. In the WinForms variant that will no longer work so we promote the local variables to the class level of the form.

The using statements are basically a try/catch/finally block with a call to Dispose in the finally block. The closing and disposing becomes now our own responsibility so in the stop the Disposemethod of both the Writer and the Capture is called after which the class variables are assigned a null value.

You end up with something like this:

public class Form1:Form 
{
    // other stuff 

    private WasapiCapture capture = null;
    private WaveWriter w = null;

    private void start_Click(object sender, EventArgs e)
    {
            capture = new WasapiLoopbackCapture();
            capture.Initialize();
            //create a wavewriter to write the data to
            w = new WaveWriter("dump.wav", capture.WaveFormat));
            //setup an eventhandler to receive the recorded data
            capture.DataAvailable += (s, capData) =>
            {
                //save the recorded audio
                w.Write(capData.Data, capData.Offset, capData.ByteCount);
            };
            //start recording
            capture.Start();     
    }

    private void stop_Click(object sender, EventArgs e)
    {
        if (w != null && capture !=null)
        { 
            //stop recording
            capture.Stop();
            w.Dispose();
            w = null;
            capture.Dispose();
            capture = null;
        }
    }
}

The above code was adapted from this answer by user thefiloe

Upvotes: 3

Related Questions