C # camera video recording based on Aforge

Source: Internet
Author: User
Tags time interval
1. Overview

Recently engaged in Huawei's CDN (-_-| | -_-|| -_-|| ), less time to write things. I recently learned to use Aforge on C # to record camera video and compress the code with interest. Overall, the third party. NET Visual Development library is relatively stable (aforge lib download, offline help document download). However, because this Third-party library maintenance is not good, resulting in incompatibility problems. Here to share these with you, hope to help you.

There are a number of classes that are used to record local video using the Aforge third-party Library:filterinfocollection, Videocapturedevice, Videosourceplayer, Videofilewriter . Below I will briefly introduce the methods involved in these several categories.

Filterinfocollection:

This class is mainly used for camera video input device list detection. is the System.Collections.CollectionBase class that inherits from C #.


This is how the class is invoked on the offline help document:


The parameters that the constructor passes in are the type of signal that needs to be collected, and he has other input types (such as sounds):


Videocapturedevice:

This is some of the member functions and variables in the class



This class is the device that is going to select the video input, and his constructor is


When multiple devices may exist during actual use, the input device can be specified with the second parameter. This is the initialization.


In the actual use of this example, the above class event Newframe function is responded to and the current frame is extracted.

Videosourceplayer:

The class, which is called in the Aforge.control, is added here to be used as a camera feature and is not covered here.

Videofilewriter:

This class is the video write operation class, mainly realizes the video file compression and writes to the file.

In this example, the Videofilewriter.open () function is used to set the height, width, frame rate, and encoding type of the recorded video.


This is the video encoding format supported by the third party class library


You can then write the current frame to the video file using the following function.


2. To achieve

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Windows.Forms;

Using System.Timers;
Using Aforge using Aforge;
Using Aforge.video;
Using AForge.Video.DirectShow;
Using AForge.Video.FFMPEG;

Using Aforge.controls; namespace Video_record {public partial class Form1:form {public Form1 () {Initiali
        Zecomponent (); //Close window response function private void button2_click (object sender, EventArgs e) {if (this.writer . IsOpen) {MessageBox.Show ("the video stream is not finished, please click the end recording.")
                "," Error ", MessageBoxButtons.OK, Messageboxicon.error);
            Return
            } this.videoSource.SignalToStop ();
            This.videoSource.WaitForStop ();
            This.videoSourcePlayer.SignalToStop ();
           This.videoSourcePlayer.WaitForStop (); This.
            Hide (); This.
            Close (); This.
        Dispose ();  Private Filterinfocollection videodevices;     Camera equipment private Videocapturedevice videosource;    The source of the video selection private Videosourceplayer Videosourceplayer;     Aforge Control control private Videofilewriter writer;   Write to video private bool Is_record_video = false;
        Whether to start video System.Timers.Timer Timer_count;

        int tick_num = 0;

            Form initialization function private void Form1_Load (object sender, EventArgs e) {this.label5.Visible = false;
            This.videosourceplayer = new AForge.Controls.VideoSourcePlayer ();
            This.videosource = new Videocapturedevice ();

            This.writer = new Videofilewriter ();
            Sets the video encoding format THIS.COMBOBOX_VIDEOECODE.ITEMS.ADD ("Raw");
            THIS.COMBOBOX_VIDEOECODE.ITEMS.ADD ("MPEG2");
            THIS.COMBOBOX_VIDEOECODE.ITEMS.ADD ("FLV1"); THIS.COMBOBOX_VIDEOECODE.ITEMS.ADD ("h263p"); This.combobox_videoecode.
            Items.Add ("Msmpeg4v3"); This.combobox_videoecode.
            Items.Add ("Msmpeg4v2"); This.combobox_videoecode.
            Items.Add ("WMV2"); This.combobox_videoecode.
            Items.Add ("WMV1"); This.combobox_videoecode.
            Items.Add ("MPEG4"); This.combobox_videoecode.

            SelectedIndex = 1; Set Video source try {//Enumerate all video input devices videodevices = new Filterinfocollecti

                On (Filtercategory.videoinputdevice);   if (Videodevices.count = = 0) throw new ApplicationException (); Camera device not found foreach (FilterInfo device in videodevices) {This.combob Ox_camera. Items.Add (device.
                Name); }//this.combobox_camera.   SelectedIndex = 0; Comment out, select the camera source will only trigger the display of camera information} catch (ApplicationException) {Videode vices = null;
                MessageBox.Show ("No camera device found", "error", MessageBoxButtons.OK, Messageboxicon.error);   }//Stopwatch This.timer_count = new System.Timers.Timer (); Instantiate the Timer class, setting a time interval of 10000 milliseconds; This.timer_count.   Elapsed + = new System.Timers.ElapsedEventHandler (tick_count); To execute an event at the time of arrival; This.timer_count.   Autoreset = true; Whether the setting is executed once (false) or always (true); This.timer_count.
        Interval = 1000;
        ///Video Source Select dropdown box after the selection of response function private void combobox_camera_selectedindexchanged (object sender, EventArgs e)
            {int selected_index = This.comboBox_camera.SelectedIndex; This.videosource = new Videocapturedevice (videodevices[selected_index).
            monikerstring);
            Set Newframe event handler Videosource.newframe + = new Newframeeventhandler (show_video);
            Videosource.start ();
            Videosourceplayer.videosource = VideoSource;
  Videosourceplayer.start ();          This.label5.Text = "in connection ...";
            This.label5.Visible = true;
        Isshowed = true;
        bool isshowed = true;
            Trigger function for new frame private void Show_video (object sender, Newframeeventargs EventArgs) {if (isshowed)
                {this.label5.Visible = false;
            isshowed = false;    } Bitmap Bitmap = Eventargs.frame; Gets to a frame image picturebox1.image = Image.fromhbitmap (bitmap.
            Gethbitmap ()); if (Is_record_video) {writer.
            Writevideoframe (bitmap); Photo//Image button response function private void button1_click (object sender, EventArgs e) {if
            (this.videoSource.IsRunning && this.videoSourcePlayer.IsRunning)
                {Bitmap Bitmap = This.videoSourcePlayer.GetCurrentVideoFrame (); Bitmap.
       Save ("Img.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);     Else MessageBox.Show ("Camera not Running", "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        ; //Start Video button response function private void Button_start_click (object sender, EventArgs e) {int Widt    h = 640;   width of recording video int height = 480;

            Record the height of the video int fps = 9; Create a video file String Video_format = This.comboBox_videoecode.Text.Trim ();
                Gets the selected video encoding if (this.videoSource.IsRunning && this.videoSourcePlayer.IsRunning) { if ( -1!= Video_format. IndexOf ("MPEG")) {writer.
                Open ("Test.avi", width, height, fps, VIDEOCODEC.MPEG4); else if ( -1!= Video_format. IndexOf ("WMV")) {writer.
                Open ("test.wmv", width, height, fps, VIDEOCODEC.WMV1); else {writer. Open ("test.mkv", Width, HeigHT, FPS, videocodec.default); Else MessageBox.Show ("Cannot record video without video source input.")

            "," Error ", MessageBoxButtons.OK, Messageboxicon.error); Timer_count.
            Enabled = true;//Whether the System.Timers.Timer.Elapsed event is executed; this.label5.Visible = true;
            This.label5.Text = "REC";
        This.is_record_video = true; //Stop Recording video response function private void Button_stop_click (object sender, EventArgs e) {This.lab El5.
            Visible = false;
            This.is_record_video = false;
            This.writer.Close (); This.timer_count.
            Enabled = false;
        Tick_num = 0; }//Pause button response function private void Button3_Click (object sender, EventArgs e) {if (This.button
                3.text.trim () = "Pause video") {This.is_record_video = false;
                This.label5.Visible = false;
                This.button3.Text = "restore Video"; Timer_count.    Enabled = false;
            Pause the timing return;
                } if (This.button3.Text.Trim () = "restore Video") {This.is_record_video = true; Timer_count.     Enabled = true;
                Recovery Timer this.label5.Visible = true;
            This.button3.Text = "Pause video";
            }//Timer response function public void Tick_count (object source, System.Timers.ElapsedEventArgs e) {
            tick_num++;

            int temp = Tick_num;

            int sec = temp% 60;
            int min = TEMP/60;
                if (+ = min) {min = 0;
            min++;

            int hour = MIN/60; String tick = hour. ToString () + ":" + min. ToString () + ":" + sec.
            ToString ();
        This.label4.Text = tick; }
        

    }
}
3. The result

4. Errors and Precautions1. In the use of aforge this software process requires more than just the release folder to add the corresponding LIB to the project reference, in the video compression coding need to add the external folder under the relevant LIB to the program running the Debug directory
2. This error is encountered when using the mixed-mode assembly is an error that is generated for the runtime of the "v2.0.50727" version without configuring additional information. This is because the. NET Framework is incompatible, Aforge is used more like 2.0 ... -_-| |. So you need to configure it in App.config to make it compatible with the previous version, configured as follows (this is the configuration I added):
  <startup uselegacyv2runtimeactivationpolicy= "true" >
    <supportedruntime version= "v4.0". netframework,version=v4.5 "/>
    <supportedruntime version= v2.0.50727"/>
    </startup>
Here is my Demo, interested can see ....

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.