Skip to content

Quickstart guide v5.x.x

Sverre Skodje edited this page Nov 1, 2022 · 15 revisions

Basic usage

This quickstart does not cover everything, but to see all features with examples, check out the sample project.

Start a video recording to a file using default settings:

        using ScreenRecorderLib;
        
        Recorder _rec;
        void CreateRecording()
        {
            string videoPath = Path.Combine(Path.GetTempPath(), "test.mp4");
            _rec = Recorder.CreateRecorder();
            _rec.OnRecordingComplete += Rec_OnRecordingComplete;
            _rec.OnRecordingFailed += Rec_OnRecordingFailed;
            _rec.OnStatusChanged += Rec_OnStatusChanged;
	    //Record to a file
	    string videoPath = Path.Combine(Path.GetTempPath(), "test.mp4");
            _rec.Record(videoPath);
        }
        void EndRecording()
        {
            _rec.Stop(); 
        }
        private void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e)
        {
	    //Get the file path if recorded to a file
            string path = e.FilePath;	
        }
        private void Rec_OnRecordingFailed(object sender, RecordingFailedEventArgs e)
        {
            string error = e.Error;
        }
        private void Rec_OnStatusChanged(object sender, RecordingStatusEventArgs e)
        {
            RecorderStatus status = e.Status;
        }

Change the options with RecorderOptions:

            //These options must be set before starting the recording, and cannot be modified while recording.
            RecorderOptions options = new RecorderOptions
            {
                SourceOptions = new SourceOptions
                {
                    //Populate and pass a list of recordingsources.
                    RecordingSources = new List<RecordingSourceBase>()
                },
                OutputOptions = new OutputOptions
                {
                    RecorderMode = RecorderMode.Video,
                    //This sets a custom size of the video output, in pixels.
                    OutputFrameSize = new ScreenSize(1920, 1080),
                    //Stretch controls how the resizing is done, if the new aspect ratio differs.
                    Stretch = StretchMode.Uniform,
                    //SourceRect allows you to crop the output.
                    SourceRect = new ScreenRect(100, 100, 500, 500)
                },
                AudioOptions = new AudioOptions
                {
                    Bitrate = AudioBitrate.bitrate_128kbps,
                    Channels = AudioChannels.Stereo,
                    IsAudioEnabled = true,
                },
                VideoEncoderOptions = new VideoEncoderOptions
                {
                    Bitrate = 8000 * 1000,
                    Framerate = 60,
                    IsFixedFramerate = true,
                    //Currently supported are H264VideoEncoder and H265VideoEncoder
                    Encoder = new H264VideoEncoder
                    {
                        BitrateMode = H264BitrateControlMode.CBR,
                        EncoderProfile = H264Profile.Main,
                    },
                    //Fragmented Mp4 allows playback to start at arbitrary positions inside a video stream,
                    //instead of requiring to read the headers at the start of the stream.
                    IsFragmentedMp4Enabled = true,
                    //If throttling is disabled, out of memory exceptions may eventually crash the program,
                    //depending on encoder settings and system specifications.
                    IsThrottlingDisabled = false,
                    //Hardware encoding is enabled by default.
                    IsHardwareEncodingEnabled = true,
                    //Low latency mode provides faster encoding, but can reduce quality.
                    IsLowLatencyEnabled = false,
                    //Fast start writes the mp4 header at the beginning of the file, to facilitate streaming.
                    IsMp4FastStartEnabled = false
                },
                MouseOptions = new MouseOptions
                {
                    //Displays a colored dot under the mouse cursor when the left mouse button is pressed.	
                    IsMouseClicksDetected = true,
                    MouseLeftClickDetectionColor = "#FFFF00",
                    MouseRightClickDetectionColor = "#FFFF00",
                    MouseClickDetectionRadius = 30,
                    MouseClickDetectionDuration = 100,
                    IsMousePointerEnabled = true,
                    /* Polling checks every millisecond if a mouse button is pressed.
                       Hook is more accurate, but may affect mouse performance as every mouse update must be processed.*/
                    MouseClickDetectionMode = MouseDetectionMode.Hook
                },
                OverlayOptions = new OverLayOptions
                {
                    //Populate and pass a list of recording overlays.
                    Overlays = new List<RecordingOverlayBase>()
                },
                SnapshotOptions = new SnapshotOptions
                {
                    //Take a snapshot of the video output at the given interval
                    SnapshotsWithVideo = false,
                    SnapshotsIntervalMillis = 1000,
                    SnapshotFormat = ImageFormat.PNG,
                    //Optional path to the directory to store snapshots in
                    //If not configured, snapshots are stored in the same folder as video output.
                    SnapshotsDirectory = ""
                },
                LogOptions = new LogOptions
                {
                    //This enabled logging in release builds.
                    IsLogEnabled = true,
                    //If this path is configured, logs are redirected to this file.
                    LogFilePath = "recorder.log",
                    LogSeverityLevel = ScreenRecorderLib.LogLevel.Debug
                }
            };

            Recorder rec = Recorder.CreateRecorder(options); 	    

Change options during a recording with dynamic options:

            //Some options can be modified through GetDynamicOptionsBuilder() on the Recorder object with a recording in progress.
            //This example changes the volume of the audio input device to 0.
            Recorder rec = Recorder.CreateRecorder();
            //start recording...
            rec.GetDynamicOptionsBuilder()
                    .SetDynamicAudioOptions(new DynamicAudioOptions { InputVolume = 0 })
                    .Apply();

Select audio device to record:

            List<AudioDevice> inputDevices = Recorder.GetSystemAudioDevices(AudioDeviceSource.InputDevices);
            List<AudioDevice> outputDevices = Recorder.GetSystemAudioDevices(AudioDeviceSource.OutputDevices);
            AudioDevice selectedOutputDevice = outputDevices.FirstOrDefault();//select one of the devices.. Passing empty string or null uses system default playback device.
            AudioDevice selectedInputDevice = inputDevices.FirstOrDefault();//select one of the devices.. Passing empty string or null uses system default recording device.
            var AudioOptions = new AudioOptions
            {
                IsAudioEnabled = true,
                IsOutputDeviceEnabled = true,
                IsInputDeviceEnabled = true,
                AudioOutputDevice = selectedOutputDevice.DeviceName,
                AudioInputDevice = selectedInputDevice.DeviceName
            };    

If recording both an input device like a microphone and and the system output audio, the gain should be set using the volume options. By default, both sources are mixed together at 100%, which can lead to the audio clipping depending on the loudness of the source:

	    //Here both sources are set to 50% gain, which will result in a quieter recording but with guaranteed no clipping.
	    //You can configure this how you want for both sources, from 0.0 to 1.0 (or above).
            RecorderOptions options = new RecorderOptions
            {
	       AudioOptions = new AudioOptions
               {
		InputVolume = 0.5,
		OutputVolume = 0.5
               }	
            }   	    

Select source to record:

This example shows how to add one or several monitors to record.

Monitors

            var sources = new List<RecordingSourceBase>();
            //You can add main monitor by a static MainMonitor property
            var monitor1 = new DisplayRecordingSource(DisplayRecordingSource.MainMonitor);
            //Or any monitor by device name
            var monitor2 = new DisplayRecordingSource(@"\\.\DISPLAY2");
            sources.Add(monitor1);
            sources.Add(monitor2);
            //Or you can all system monitors with the static Recorder.GetDisplays() function.
            sources.AddRange(Recorder.GetDisplays());
            RecorderOptions options = new RecorderOptions
            {
                SourceOptions = new SourceOptions
                {
                    RecordingSources = sources
                }
            };

Windows

            var sources = new List<RecordingSourceBase>();
            //To get a list of recordable windows on the system, you can use the static Recorder.GetWindows() function.
            var allRecordableWindows = Recorder.GetWindows();
            sources.Add(allRecordableWindows.FirstOrDefault());
            //Or any window by passing the window handle
            IntPtr windowHandle = GetWindowHandleFromTheWindowToRecord();
            sources.Add(new WindowRecordingSource(windowHandle));

Cameras

            var sources = new List<RecordingSourceBase>();
            //To get a list of recordable cameras and other video inputs on the system, you can use the static Recorder.GetSystemVideoCaptureDevices() function.
            var allRecordableCameras = Recorder.GetSystemVideoCaptureDevices();
	    var cameraSource = allRecordableCameras.FirstOrDefault();
            //Or any input by passing the device name
            cameraSource = new VideoCaptureRecordingSource(@"\\?\my_cameras_device_path");
	    sources.Add(cameraSource);

Cameras with several available capture formats, resolution, framerate, etc. can be configured by querying the static Recorder.GetSupportedVideoCaptureFormatsForDevice function. If no format is specified, the camera default will be used.

	    var availableFormats = Recorder.GetSupportedVideoCaptureFormatsForDevice(cameraSource.DeviceName);
	    cameraSource.CaptureFormat = availableFormats.FirstOrDefault();

Videos and images

            var sources = new List<RecordingSourceBase>();
            sources.Add(new VideoRecordingSource(@"c:\MyVideo.mp4"));
            sources.Add(new ImageRecordingSource(@"c:\MyImage.jpeg"));
            sources.Add(new ImageRecordingSource(@"c:\MyAnimatedImage.gif"));

Source properties

            RecordingSourceBase source;
            source.IsVideoCaptureEnabled = true;
            //The anchor point of this source in the output canvas. This is used when the source does not exactly fill the output canvas.
            source.AnchorPoint = Anchor.TopLeft;
            //Override the size of this output
            source.OutputSize = new ScreenSize(1920, 1080);
            //Crops the source from the given rectangle.
            source.SourceRect = new ScreenRect(100, 100, 500, 500);
            //Offsets the source by the given amount on the output canvas
            source.Position = new ScreenPoint(100, 100);
            //How the source stretches when resized.
            source.Stretch = StretchMode.Uniform;

Add overlays to recording:

            //Here is a list of all supported overlay types and their properties.
            //Overlays have an offset property that is the overlay position relative to the anchor point.
            var overlays = new List<RecordingOverlayBase>();
            overlays.Add(new VideoCaptureOverlay
            {
                AnchorPoint = Anchor.TopLeft,
                Offset = new ScreenSize(100, 100),
                Size = new ScreenSize(0, 250),
                DeviceName = @"\\?\my_camera_device_name" //or null for system default camera
            });
            overlays.Add(new VideoOverlay
            {
                AnchorPoint = Anchor.TopRight,
                SourcePath = @"MyVideo.mp4",
                Offset = new ScreenSize(50, 50),
                Size = new ScreenSize(0, 200)
            });
            overlays.Add(new ImageOverlay()
            {
                AnchorPoint = Anchor.Center,
                SourcePath = @"MyImage.gif",
                Offset = new ScreenSize(0, 0),
                Size = new ScreenSize(0, 300),
                Stretch = StretchMode.Fill
            });
            overlays.Add(new DisplayOverlay()
            {
                AnchorPoint = Anchor.TopLeft,
                Offset = new ScreenSize(400, 100),
                Size = new ScreenSize(300, 0)
            });
            overlays.Add(new WindowOverlay()
            {
                AnchorPoint = Anchor.BottomRight,
                Offset = new ScreenSize(100, 100),
                Size = new ScreenSize(300, 0)
            });