Simple Recorder

In this tutorial we’re going to make a screen and audio recorder software.

Prerequisite

What this software will do?

This software will capture the screen and the audio of the computer, this allow you to record gampeplay of videogames or your activity on the computer. To make this software we’ll use LibVLCSharp(we already use it in this tutorial) to record the video, and we’ll use NAudio to record the audio, then we’ll use FFMPEG to merge the audio and the video to a single file.

What we need to install?

Just like the video player tutorial we need to create a new “Windows Form” project, then with nuget we need to install:

The form

In this tutorial we’ll use only one form and its design is pretty simple, it only has 3 buttons, one to start the recording, one to stop it and one to merge the audio and video files into one.
It should look like something like this:
Responsive image

Video Recorder Class

To keep our code clean and simple we’ll use two classes one will record the video, the other for the audio.
Let’s start by adding a “VideoRecorder” class to the project.
First thing first let’s add:

1using LibVLCSharp.Shared;

Now inside the class we need to setup the LibVLCSharp, let’s add:

1public LibVLC _libVLC;
2public MediaPlayer _mp;
3public Media _media;
4public bool _isRecording = false;

Inside the main function let’s add:

1Core.Initialize();
2_libVLC = new LibVLC("--verbose=2");
3_mp = new MediaPlayer(_libVLC);
4_media = new Media(_libVLC, "screen://", FromType.FromLocation);

--verbose=2 inside the LibVLC() allow us to see more informations inside the console, this can help us if there is any error or if something doesn’t work as expected.
screen:// is the source that we want to capture, in this case the screen(it’s the same for multi monitor setups).

Let’s create a new function StartRecVideo and inside it let’s add:

 1if(_isRecording)
 2{
 3	return;
 4}
 5_media.AddOption(":screen-fps=60");
 6_media.AddOption(":sout=#transcode{vcodec=h264,sfilter=marq:logo}:file{dst=Video.mp4}");
 7_media.AddOption(":screen-width=1920:screen-height=1080");
 8_media.AddOption(":screen-mouse-image=Mouse.png");
 9_isRecording = true;
10_mp.Play(_media);

:screen-fps=60 This means that we want to record at 60 frame per second.
sfilter=marq:logo We will not use these filters in this tutorial but i’ve already put them to let you add text and/or images to the video while recording.
:file{dst=Video.mp4} This tell what the name of the file will be.
:screen-width=1920:screen-height=1080 I set this up to record at the risolution 1920x1080, if you have a multi monitor setup this will let the video capture record only the first screen.
:screen-mouse-image=Mouse.png on the recorded file you will see that there is no mouse, this option will set any image called “Mouse.png” as the cursor, I edited a bit and used this one.
_mp.Play(_media); This will start the recording.

Now we need to stop the recording, to do that we need to create a new function StopRecVideo, inside it put:

1_mp.Stop();
2_isRecording = false;

Audio Recorder Class

In this second class we will record the audio of the computer.
Just like before, create a new class “AudioRecorder”.
On top add:

1using System.Threading;
2using NAudio.Wave;
3using NAudio.Wave.SampleProviders;

Inside the class add these variables:

1public IWaveIn _capture;
2public WaveOutEvent _waveOut;
3public WaveFileWriter _writer;
4public bool _isRecording = false;

IWaveIn _capture is the source that we’re recording.
WaveOutEvent _waveOut allow us to play audio, I’ll explain it later.
WaveFileWriter _writer let us to save the recording to a file.

Now let’s add a function StartRecAudio and inside it put:

1if (_isRecording)
2{
3    return;
4}
5_isRecording = true;
6_capture = new WasapiLoopbackCapture();
7_writer = new WaveFileWriter("Audio.wav", _capture.WaveFormat);

_capture = new WasapiLoopbackCapture(); This allow us to record from the system default device.
_writer = new WaveFileWriter("Audio.wav", _capture.WaveFormat); This create the file that will store the audio.
Then add:

 1_capture.DataAvailable += (s, a) =>
 2{
 3    _writer.Write(a.Buffer, 0, a.BytesRecorded);
 4};
 5_capture.RecordingStopped += (s, a) =>
 6{
 7    _writer.Dispose();
 8    _waveOut.Dispose();
 9    _writer = null;
10    _capture.Dispose();
11    _isRecording = false;
12};
13_capture.StartRecording();

To create the events handlers for the DataAvailable and RecordingStopped we used a lambda expressions, another way to write this without lambda expression is this:

1_capture.DataAvailable += FunctionName;
2
3//outside the main function
4void FunctionName(object s, WaveInEventArgs a)
5{
6	_writer.Write(a.Buffer, 0, a.BytesRecorded);
7}

In this case, we didn’t write so much, so using lambda expressions make the code more compact, but if you don’t like them you don’t have to.
Inside DataAvailable we’re writing to the file every sound that is played on the computer, so if no sound is played it will not record the “silence”, we’re going to fix this later.
Inside RecordingStopped we dispose everything.
_capture.StartRecording() This will simply start to record the audio.
As I tell earlier, if no sound is played on the system the recorder will pause, to let the program record even when nothing is played we’ll play a silence audio.
To do that add:

1Thread thread = new Thread(PlaySilence);
2thread.Start();

This will create a new thread that will execute the function PlaySilence, create that function and iside it write:

1var silence = new SilenceProvider((new SignalGenerator() { Frequency = 1000, Gain = 0.2 }).WaveFormat).ToSampleProvider();
2_waveOut = new WaveOutEvent();
3_waveOut.Init(silence);
4_waveOut.Play();
5while (_waveOut.PlaybackState == PlaybackState.Playing)
6{
7    Thread.Sleep(500);
8}

With this code we created the silence, then we created a new WaveOutEvent and we played it.
All this code allow us to record the audio even when nothing is played because this silence will always trigger the DataAvailable event.

The last function of the class that we need to create is StopRecAudio, inside it we need to write:

1if (!_isRecording)
2{
3    return;
4}
5_capture.StopRecording();

Form Code

Now we can add the code to the form.
First, let’s add the 2 classes that we’ve created.

1private AudioRecorder audioRec = new AudioRecorder();
2private VideoRecorder videoRec = new VideoRecorder();

Now inside the “start rec” button write:

1audioRec.StartRecAudio();
2videoRec.StartRecVideo();

Inside the “stop rec” button put:

1audioRec.StopRecAudio();
2videoRec.StopRecVideo();

In the last button we’ll run a batch file that will execute FFMPEG.
To download FFMPEG go here: https://ffmpeg.org
Copy the 3 .exe file from the FFMPEG and put them inside your working directory(debug or release).
Now create a .bat file(I call it file.bat) and inside it write:

1ffmpeg -i video.mp4 -i audio.wav -filter:v fps=fps=60 output.mp4
2pause

Let’s add the code to the third button:

1System.Diagnostics.Process proc = new System.Diagnostics.Process();
2proc.StartInfo.FileName = "file.bat";
3proc.Start();

What’s happening

When we click the “rec button” we’re recording the video with LibVLCSharp and store it in a Video.mp4 file, but we’re also recording the audio with NAudio and store it inside the Audio.wav file(Remeber both files will be overwritten if you start a new recording).
When we stop the recording we have the audio and the video in separate files, to merge them into one we’ve used FFMPEG, and we’ve created an output.mp4 file(if the file exist it will ask to you if you want to overwrite the file).

You can look at the full source code below.

Source Code

Form1.Designer.cs

 1namespace ScreenRecorder
 2{
 3    partial class Form1
 4    {
 5        private System.ComponentModel.IContainer components = null;
 6
 7        protected override void Dispose(bool disposing)
 8        {
 9            if (disposing && (components != null))
10            {
11                components.Dispose();
12            }
13            base.Dispose(disposing);
14        }
15
16        private void InitializeComponent()
17        {
18            this.button1 = new System.Windows.Forms.Button();
19            this.button2 = new System.Windows.Forms.Button();
20            this.button3 = new System.Windows.Forms.Button();
21            this.SuspendLayout();
22            // 
23            // button1
24            // 
25            this.button1.Location = new System.Drawing.Point(12, 12);
26            this.button1.Name = "button1";
27            this.button1.Size = new System.Drawing.Size(75, 23);
28            this.button1.TabIndex = 0;
29            this.button1.Text = "Start Rec";
30            this.button1.UseVisualStyleBackColor = true;
31            this.button1.Click += new System.EventHandler(this.button1_Click);
32            // 
33            // button2
34            // 
35            this.button2.Location = new System.Drawing.Point(93, 12);
36            this.button2.Name = "button2";
37            this.button2.Size = new System.Drawing.Size(75, 23);
38            this.button2.TabIndex = 1;
39            this.button2.Text = "Stop Rec";
40            this.button2.UseVisualStyleBackColor = true;
41            this.button2.Click += new System.EventHandler(this.button2_Click);
42            // 
43            // button3
44            // 
45            this.button3.Location = new System.Drawing.Point(174, 12);
46            this.button3.Name = "button3";
47            this.button3.Size = new System.Drawing.Size(101, 23);
48            this.button3.TabIndex = 2;
49            this.button3.Text = "Make Single File";
50            this.button3.UseVisualStyleBackColor = true;
51            this.button3.Click += new System.EventHandler(this.button3_Click);
52            // 
53            // Form1
54            // 
55            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
56            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
57            this.ClientSize = new System.Drawing.Size(290, 45);
58            this.Controls.Add(this.button3);
59            this.Controls.Add(this.button2);
60            this.Controls.Add(this.button1);
61            this.Name = "Form1";
62            this.Text = "Form1";
63            this.ResumeLayout(false);
64
65        }
66
67        #endregion
68
69        private System.Windows.Forms.Button button1;
70        private System.Windows.Forms.Button button2;
71        private System.Windows.Forms.Button button3;
72    }
73}
74

Form1.cs

 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel;
 4using System.Data;
 5using System.Drawing;
 6using System.Linq;
 7using System.Text;
 8using System.Threading.Tasks;
 9using System.Windows.Forms;
10
11namespace ScreenRecorder
12{
13    public partial class Form1 : Form
14    {
15        private AudioRecorder audioRec = new AudioRecorder();
16        private VideoRecorder videoRec = new VideoRecorder();
17        public Form1()
18        {
19            InitializeComponent();
20        }
21
22        private void button1_Click(object sender, EventArgs e)
23        {
24            audioRec.StartRecAudio();
25            videoRec.StartRecVideo();
26        }
27
28        private void button2_Click(object sender, EventArgs e)
29        {
30            audioRec.StopRecAudio();
31            videoRec.StopRecVideo();
32        }
33
34        private void button3_Click(object sender, EventArgs e)
35        {
36            System.Diagnostics.Process proc = new System.Diagnostics.Process();
37            proc.StartInfo.FileName = "file.bat";
38            proc.Start();
39        }
40    }
41}

VideoRecorder.cs

 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using System.Threading.Tasks;
 6using LibVLCSharp.Shared;
 7
 8namespace ScreenRecorder
 9{
10    class VideoRecorder
11    {
12
13        public LibVLC _libVLC;
14        public MediaPlayer _mp;
15        public Media _media;
16        public bool _isRecording = false;
17        public VideoRecorder()
18        {
19            Core.Initialize();
20            _libVLC = new LibVLC("--verbose=2");
21            _mp = new MediaPlayer(_libVLC);
22            _media = new Media(_libVLC, "screen://", FromType.FromLocation);
23        }
24
25        public void StartRecVideo()
26        {
27            if(_isRecording)
28            {
29                return;
30            }
31            _media.AddOption(":screen-fps=60");
32            _media.AddOption(":sout=#transcode{vcodec=h264,sfilter=marq:logo}:file{dst=Video.mp4}");
33            _media.AddOption(":screen-width=1920:screen-height=1080");
34            _media.AddOption(":screen-mouse-image=Mouse.png");
35            _isRecording = true;
36            _mp.Play(_media);
37
38        }
39
40        public void StopRecVideo()
41        {
42            if (!_isRecording)
43            {
44                return;
45            }
46            _mp.Stop();
47            _isRecording = false;
48        }
49    }
50}
51

AudioRecorder.cs

 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using NAudio.Wave;
 8using NAudio.Wave.SampleProviders;
 9
10namespace ScreenRecorder
11{
12    class AudioRecorder
13    {
14
15        public IWaveIn _capture;
16        public WaveOutEvent _waveOut;
17        public WaveFileWriter _writer;
18        public bool _isRecording = false;
19
20        public void StartRecAudio()
21        {
22            if (_isRecording)
23            {
24                return;
25            }
26            _isRecording = true;
27            _capture = new WasapiLoopbackCapture();
28            _writer = new WaveFileWriter("Audio.wav", _capture.WaveFormat);
29            _capture.DataAvailable += (s, a) =>
30            {
31                _writer.Write(a.Buffer, 0, a.BytesRecorded);
32            };
33            _capture.RecordingStopped += (s, a) =>
34            {
35                _writer.Dispose();
36                _waveOut.Dispose();
37                _writer = null;
38                _capture.Dispose();
39                _isRecording = false;
40            };
41            _capture.StartRecording();
42            
43            Thread thread = new Thread(PlaySilence);
44            thread.Start();
45        }
46
47        public void StopRecAudio()
48        {
49            if (!_isRecording)
50            {
51                return;
52            }
53            _capture.StopRecording();
54        }
55
56        public void PlaySilence()
57        {
58            var silence = new SilenceProvider((new SignalGenerator() { Frequency = 1000, Gain = 0.2 }).WaveFormat).ToSampleProvider();
59            _waveOut = new WaveOutEvent();
60            _waveOut.Init(silence);
61            _waveOut.Play();
62            while (_waveOut.PlaybackState == PlaybackState.Playing)
63            {
64                Thread.Sleep(500);
65            }
66        }
67    }
68
69}

Conclusion

In this tutorial we learned how to:

That’s a lot of things, if you want further explanations contact me on Twitter 👍
Did you know that I used this program to record the video of the “video player” tutorial?

Did you like this tutorial?
Did you find it useful?
Let me know on Twitter! @CodeSailer