Tuesday, 30 July 2019

C# - Windows WASAPI - Record loopback

I have been playing with multimedia programs such as ffmpeg which has wonderful video processing capabilities in converting/re-encoding one file format to another but I was less impressed by its sound processing as it was always outclassed by Audacity. Audacity is king but I wonder how best to replicate its functionality from the command line or from code. In this post, I show the C# way to use the WASAPI interface via CSCore to record the sound loopback.

Give yourself a console program, and then NuGet CSCore by Florian (thanks) and then copy in the following code


using CSCore.Codecs.WAV;
using CSCore.SoundIn;

using System;

namespace CSCoreWasapiLoopbackExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WasapiCapture capture = new WasapiLoopbackCapture())
            {
                //if nessesary, you can choose a device here
                //to do so, simply set the device property of the capture to any MMDevice
                //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

                Console.WriteLine("Waiting, press any key to start");
                Console.ReadKey();
                //initialize the selected device for recording
                capture.Initialize();

                //create a wavewriter to write the data to
                using (WaveWriter w = new WaveWriter("dump.wav", capture.WaveFormat))
                {
                    //setup an eventhandler to receive the recorded data
                    capture.DataAvailable += (s, e) =>
                    {
                        //save the recorded audio
                        w.Write(e.Data, e.Offset, e.ByteCount);
                    };

                    //start recording
                    capture.Start();

                    Console.WriteLine("Started, press any key to stop");
                    Console.ReadKey();

                    //stop recording
                    capture.Stop();
                }
            }
        }
    }
}

So now you can record your computer's speaker output.

No comments:

Post a Comment