c#屏幕录制(经典)(含源码和AForge.Video.FFMPEG.DLL)及填坑办法
? ? ? ? 一直覺得.net在多媒體處理方面渣得不行。最近需要做一個攝像頭的程序,為了方便,用了AForge這個開源項目。AForge項目中有AForge.Video和AForge.Video. DirectShow這兩個子項目,可以方便的調用攝像頭。但是這兩個項目最終只能取得視頻幀,并不能保存為視頻文件。經高人指點,AForge還有一個子項目AForge.Video.FFMPEG,它可以將圖片壓制成Avi視頻格式。不過這個AForge.Video.FFMPEG在實際使用的時候會遇到不少坑,下面我將我在這次使用中遇到的坑分享給大家。
?? ??AForge.NET是一個專門為開發者和研究者基于C#框架設計的,該庫是一個開源項目,他包括計算機視覺與人工智能,圖像處理,神經網絡,遺傳算法,機器學習,模糊系統,機器人控制等領域,提供很多圖像的處理,和視頻處理功能
? ? ? ??這個框架由一系列的類庫組成。主要包括有:
?AForge.Imaging —— 一些日常的圖像處理和過濾器
?AForge.Vision —— 計算機視覺應用類庫
?AForge.Neuro —— 神經網絡計算庫AForge.Genetic -進化算法編程庫
?AForge.MachineLearning —— 機器學習類庫
?AForge.Robotics —— 提供一些機器人的工具類庫
?AForge.Video —— 一系列的視頻處理類庫
?AForge.Fuzzy —— 模糊推理系統類庫
?AForge.Controls—— 圖像,三維,圖表顯示控件
官網:http://www.aforgenet.com/
Aforge.Net子項目有個AForge.Video.VFW提供了對Avi文件的操作,AForge后面加入了子項目?AForge.Video.FFMPEG?通過FFmpeg庫,提供了對大量視頻格式的支持,我們都知道,FFmpeg是一個非常強大的視頻處理類庫,同樣也是開源的,不過?AForge.Video.FFMPEG?還處于實驗階段,目標是用 FFmpeg?取代?AForge.Video.VFW?提供一個更好的對視頻文件操作的庫,但是該庫值目前提供了對視頻數據的讀寫,不支持對音頻文件的讀寫,可能以后會支持?
第一坑:引用
你要用AForge.Video.FFMPEG,當然第一步是引用啦。但這個AForge.Video.FFMPEG并不能像AForge其他項目一樣可以用Visual Studio自帶的NuGet去獲得,你會發現NuGet上根本找不到這個項目。
找不到么,那我就去官網找好了,咱們可以去AForge項目官網下載AForge項目的源碼和已編譯文件。不過這里有倆問題:
AForge項目官網打開速度非常非常非常慢,你可以點鏈接打開官網,然后打開游戲玩一會兒。(這里我就給各位放個AForge下載頁直鏈:http://www.aforgenet.com/framework/downloads.html)
AForge項目的源碼和生成文件最終都是放在GoogleCode上的,國內你懂得。不過這邊我們就可以用的小花招就是用迅雷之類的下載器下載,他們的離線下載是可以翻墻的。
我是選擇了“Download Installer”,右鍵選擇“復制鏈接地址”,然后放進迅雷下載。
下載下來之后是一個壓縮包,AForge.Video.FFMPEG.dll就放在壓縮包的Release文件夾中。
第二坑:調用
剛剛我們從官網下載下來了AForge.Video.FFMPEG.dll,接下來調用就好了對吧。
然而并不是,你只是一腳踏進了一個深坑罷了,為什么說是深坑呢?因為這個dll調用非常非常的惡心。
我們來看一下有多惡心,首先我們假設我們已經在項目中已經添加了AForge.Video和AForge.Video.FFMPEG這二個類庫。
然后修改Main函數:
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace ConsoleRecoderTest {class Program{static void Main(string[] args){ScreenRecorderTemplate tmp = new ScreenRecorderTemplate(){IsStartUp = false,StartDateTime = DateTime.Now,StopDateTime = DateTime.Now.AddMinutes(2)};new ScreenRecorderTool(tmp).StartRecording();Console.WriteLine("complete");Console.Read();}} }按F5調試,瞬間爆炸:
發生這個問題的原因比較簡單,因為這個AForge.Video.FFMPEG使用VC++寫的,編譯的時候已經被編譯成本地代碼,而我們現在C#一般目標平臺都是“Any CPU”,所以會發生這個問題。
解決方案就是不再選擇使用“Any CPU”作為目標平臺,改成“x86”或者“x64”。因為x86可以跑在x64上,而x64不能在x86上跑,所以我選擇了x86。
現在再按F5啟動調試,再一次瞬間爆炸【冷漠臉】。
怎么說呢,起碼出錯提示換了對吧【冷漠臉】。
那么這次又是出什么問題了呢。
咱們現在用的是AForge.Video.FFMPEG對吧。我們都知道FFMPEG是一個著名的開源多媒體處理項目對吧,這個AForge.Video.FFMPEG其實是在內部調用FFMPEG來工作的。所以這個FileNotFoundException其實是AForge.Video.FFMPEG找不到FFMPEG的文件所以拋出來的。AForge.Video.FFMPEG依賴的FFMPEG組件其實已經放在了剛剛下載下來的壓縮包的\Externals\ffmpeg\bin目錄下:
我們把這個8個文件復制到程序目錄下,注意我們剛剛改過目標平臺了,現在程序編譯輸出的目錄已經是\bin\x86\Debug,不要復制錯了。
復制好之后我們繼續按F5調試程序。
嗯,爆炸了,我已經習慣了【冷漠臉】
這次問題的原因是什么呢……
其實是因為我的項目目標框架是.net Framework 4.0,而AForge官方在編譯AForge.Video.FFMPEG.dll的時候,目標框架選的是.net Framework 2.0……
在.net Framework 4.0以前,由于程序運行環境本質還是.net Framework 2.0,并且.net Framework 2.0兼容.net Framework 1.0和1.1,但在升級到.net Framework 4.0時,.NET的內核作了重大調整,以前在.net Framework 2.0或.net3.5中生成的程序集,如果要在.net Framework 4.0下運行,需要在配置文件中指定此應用程序支持的公共語言運行時版本和啟用.net Framework 2.0運行時激活策略。
解決方案有三種:
降低自己項目的目標.net Framework版本;
修改Config文件;
重新編譯Video.FFMPEG。
這里我就講一下方法二,
在Visual Studio中按Ctrl+Shift+A,打開“添加新項”窗口,選擇“應用程序配置文件”,再點擊“添加”(vs2017創建的時候已經自帶了App.config無需再次添加)
打開新建的App.Config文件,在<configuration>和</configuration>標簽中加入以下內容:
<startup useLegacyV2RuntimeActivationPolicy="true"><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup>添加完成后,按F5啟動調試。
終于一切正常。
錄制的視頻在文件運行目錄下:
項目的引用項:
使用的開源的視頻處理組件AForge,當然它所包含的功能遠不止于此,想了解更多到官網上去看吧。一下代碼主要是錄制桌面屏幕,每20秒存入一個視頻文件,可以為有類似需要的通知提供一點幫助。
ScreenRecorderTool.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; //using Accord.Video; //using Accord.Video.FFMPEG; using AForge.Video; using AForge.Video.FFMPEG;namespace ConsoleRecoderTest {/// <summary>/// 比特率/// </summary>public enum BitRate : int{_50kbit = 5000,_100kbit = 10000,_500kbit = 50000,_1000kbit = 1000000,_2000kbit = 2000000,_3000kbit = 3000000}/// <summary>/// 屏幕錄制模板/// </summary>public class ScreenRecorderTemplate{/// <summary>/// 模板名稱/// </summary>public string TmpName { get; set; }/// <summary>/// 錄屏開始時間/// </summary>public DateTime? StartDateTime { get; set; }/// <summary>/// 錄屏結束時間/// </summary>public DateTime? StopDateTime { get; set; }/// <summary>/// 是否為開機啟動/// </summary>public bool IsStartUp { get; set; }}/// <summary>/// 屏幕錄制工具類/// </summary>public class ScreenRecorderTool{#region Fieldsprivate int screenWidth;private int screenHight;private int bitRate = (int)BitRate._500kbit;private int frameRate = 5;//默認幀率為5private bool isRecording;private string saveFolderPath;private string fileName;private Stopwatch stopWatch;private Rectangle screenArea;private VideoFileWriter videoWriter;private ScreenCaptureStream videoStreamer;private VideoCodec videoCodec = VideoCodec.MSMPEG4v2;private ScreenRecorderTemplate recorderTmp;private static object key = new object();#endregion/// <summary>/// 是否正在錄制/// </summary>private bool IsRecording{get{lock (key){return isRecording;}}set{lock (key){isRecording = value;}}}public ScreenRecorderTool(ScreenRecorderTemplate recorderTmp){this.recorderTmp = recorderTmp;this.screenWidth = SystemInformation.VirtualScreen.Width;this.screenHight = SystemInformation.VirtualScreen.Height;this.IsRecording = false;this.SaveFolderPath = AppDomain.CurrentDomain.BaseDirectory;this.stopWatch = new Stopwatch();this.screenArea = Rectangle.Empty;SetScreenArea();}/// <summary>/// 視頻保存位置/// </summary>private string SaveFolderPath{get { return this.saveFolderPath; }set{if (string.IsNullOrEmpty(value)){throw new ArgumentNullException("saveFolderpath", "保存路徑不能為空");}this.saveFolderPath = value;}}/// <summary>/// 視頻文件名稱/// </summary>private string FileName{get { return this.fileName; }set{if (string.IsNullOrEmpty(value)){throw new ArgumentNullException("fileName", "File name can not be empty or null");}this.fileName = value;}}/// <summary>/// 完成一幀錄制的事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void video_NewFrame(object sender, NewFrameEventArgs e){if (this.IsRecording){if (videoWriter != null){this.videoWriter.WriteVideoFrame(e.Frame);}if (this.stopWatch.Elapsed.Seconds >= 20){Console.WriteLine("超過指定時間,寫入文件");StopRecording();}}else{videoStreamer.SignalToStop();videoWriter.Close();videoWriter.Dispose();//GC.Collect();Console.WriteLine("停止錄制");if (recorderTmp.IsStartUp)//開機錄制{StartRecording();}else{if (DateTime.Now <= recorderTmp.StopDateTime.Value){Console.WriteLine("記錄重啟錄制");StartRecording();}else{Console.WriteLine("時間到不再錄制");}}}}/// <summary>/// 設置必要參數打開視頻寫入工具/// </summary>private void InitializeRecordingParameters(){if (!this.IsRecording){this.IsRecording = true;CreateCatalog();this.FileName = saveFolderPath + string.Format(@"{0}-{1}.avi","MSR",DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));this.videoWriter.Open(this.FileName, this.screenWidth, this.screenHight, this.frameRate, this.videoCodec, this.bitRate);}}/// <summary>/// 創建目錄/// </summary>private void CreateCatalog(){if (saveFolderPath == AppDomain.CurrentDomain.BaseDirectory){var catalog = SaveFolderPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\";if (!System.IO.Directory.Exists(catalog)){System.IO.Directory.CreateDirectory(catalog);}SaveFolderPath = catalog;}}/// <summary>/// 設置屏幕錄制區域為全屏/// </summary>private void SetScreenArea(){foreach (Screen screen in Screen.AllScreens){this.screenArea = Rectangle.Union(this.screenArea, screen.Bounds);}if (this.screenArea == Rectangle.Empty){//logger.Error("沒有獲取到屏幕信息");throw new InvalidOperationException("Screan area can not be set");}}/// <summary>/// 舊文件清理(避免文件大小超標)/// </summary>private void ClearOldVideo(){}#region public method/// <summary>/// 打開視頻流開始錄制/// </summary>public void StartRecording(){if (recorderTmp == null){Console.WriteLine("模板不能為空");return;}if (!recorderTmp.IsStartUp){if (!recorderTmp.StartDateTime.HasValue|| !recorderTmp.StopDateTime.HasValue|| recorderTmp.StartDateTime.Value > recorderTmp.StopDateTime.Value){Console.WriteLine("模板不正確");return;}}this.videoWriter = new VideoFileWriter();InitializeRecordingParameters();this.videoStreamer = new ScreenCaptureStream(this.screenArea);this.videoStreamer.NewFrame += new NewFrameEventHandler(video_NewFrame);this.videoStreamer.Start();this.stopWatch.Start();this.IsRecording = true;Console.WriteLine("開始錄制...");}/// <summary>/// 停止錄制/// </summary>public void StopRecording(){this.stopWatch.Reset();this.IsRecording = false;}#endregion} }示例調用:
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace ConsoleRecoderTest {class Program{static void Main(string[] args){ScreenRecorderTemplate tmp = new ScreenRecorderTemplate(){IsStartUp = false,StartDateTime = DateTime.Now,StopDateTime = DateTime.Now.AddMinutes(2)};new ScreenRecorderTool(tmp).StartRecording();Console.WriteLine("complete");Console.Read();}} }補充:
直接運行的話有問題,frameRate = 5;//默認幀率為5,實際上寫在視頻里是30秒! 問題出在幀率與截屏間隔不對。`//this.videoStreamer = new ScreenCaptureStream(this.screenArea);//要加錄制間隔時間this.videoStreamer = new ScreenCaptureStream(this.screenArea, 1000 / frameRate); `另外 this.stopWatch.Elapsed.Seconds >= 20要改成21,因為大于等于20的話就停止的話實際上就只錄了19秒,所有要改為21 `if (this.stopWatch.Elapsed.Seconds >= 21)源碼、播放器、AForge.NET Framework-2.2.5.exe下載地址:
鏈接:https://pan.baidu.com/s/11O8z8Fj4JyMqgQ3ybxZ3ZQ
提取碼:5fxo
參考鏈接:
?http://www.diqisoft.com/technical/20087.htm
https://www.cnblogs.com/yyq745201/p/5334294.html
技術群:?需要進技術群學習交流的請添加小編微信,切記備注:加群,對以上內容有什么疑問也可以直接和小編直接溝通交流!? ???
小編微信:mm1552923 ??
公眾號:dotNet編程大全? ? ??
總結
以上是生活随笔為你收集整理的c#屏幕录制(经典)(含源码和AForge.Video.FFMPEG.DLL)及填坑办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐:Flowchart 一种通过文本方
- 下一篇: 通过Rancher Desktop在桌面