基本在Windows下的錄像程序在底層都是使用了Microsoft的DirectShow接口,對於DirectShow有一個.net的wrapper,稱作DirectShowLib。但是封裝地並不充分,換個角度說你還是需要知道DirectShow的API然后才能編寫攝像頭程序,有沒有封裝地更好地呢,當然有的:).我們可以使用AForge的封裝在30分鍾左右寫出一個攝像程序。
下面是關鍵代碼:
VideoFileWriter writer = new VideoFileWriter(); VideoCaptureDevice videoSource = null; System.Diagnostics.Stopwatch timer = null; private void video_NewFrame(object sender,NewFrameEventArgs eventArgs) { // get new frame Bitmap bitmap = eventArgs.Frame; //image.SetPixel(i % width, i % height, Color.Red); writer.WriteVideoFrame(bitmap, timer.Elapsed); } private void btnStart_Click(object sender, EventArgs e) { VideoCaptureDeviceForm videoSettings = new VideoCaptureDeviceForm(); var result = videoSettings.ShowDialog(this); if (result == System.Windows.Forms.DialogResult.Cancel) { return; } // create video source videoSource = videoSettings.VideoDevice; // set NewFrame event handler videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame); // start the video source videoSource.Start(); var fileName = string.Format(@"C:\temp\capv\{0}.flv", Guid.NewGuid().ToString()); FileInfo fInfo = new FileInfo(fileName); if (!Directory.Exists(fInfo.DirectoryName)) { Directory.CreateDirectory(fInfo.DirectoryName); } // create new video file writer.Open(fileName, 640, 480, 30, VideoCodec.FLV1); //start a timer to sync the video timeline timer = System.Diagnostics.Stopwatch.StartNew(); ShowCurrentStatus("running"); } private void btnStop_Click(object sender, EventArgs e) { videoSource.SignalToStop(); videoSource.WaitForStop(); writer.Close(); ShowCurrentStatus("stop"); }
AForge不僅對DirectShow進行了封裝,還提供了圖片處理的函數,可以用來處理圖片,比如一些濾鏡。其介紹在這里,文檔在這里。
NOTE:需要注意的是源碼中我使用了AForge.Video.FFMPEG的命名空間,用來保存視頻編碼,其在底層用了ffmpeg的類庫,所以運行程序時需要avcodec-53.dll等類庫在場。你可以從AForge的類庫包的Externals\ffmpeg\bin中找到這些文件。