当前位置: > 热闻

Aforge视频采集,抓取图片,录制视频,WPF下使用Image控件显示视频

时间:2022-04-23 15:38:34 热闻 我要投稿

1.项目->添加引用

AForge

AForge.Video.DirectShow

AForge.Video

AForge.Video.FFMPEG

AForge.Video.Controls

2.使用AForge.Video.FFMPEG录制视频需要以下设置

1)配置管理器->平台改成:x86

2)App.config修改成:



3)复制AForge.NET Framework-2.2.5-(libs only)Externalsffmpegbin目录下所有文件至

ProjectsWpfApplication3WpfApplication3binx86Debug(你的项目Debug目录下)

3.视频采集

1)WPF添加VideoSourcePlayer控件,因为是winforms控件,需要用到WindowsFormsHost


2)获取视频设备,开启视频

private FilterInfoCollection videoDevices;

private VideoCaptureDevice div = null;

// 设定初始视频设备

videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

if (videoDevices.Count > 0)

{ // 默认设备

div = new VideoCaptureDevice(videoDevices[0].MonikerString);

sourcePlayer.VideoSource = div;

}

sourcePlayer.Start();

4.抓取图片

System.Windows.Controls.Image image = new System.Windows.Controls.Image();

image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(

sourcePlayer.GetCurrentVideoFrame().GetHbitmap(),

IntPtr.Zero,

Int32Rect.Empty,

BitmapSizeOptions.FromEmptyOptions());

5.录制视频

1)利用NewFrame事件,两种方式

一是VideoSourcePlayer控件的NewFrame事件:private void sourcePlayer_NewFrame(object sender, ref Bitmap image)

利用控件生成事件代码:

注意:private void sourcePlayer_NewFrame(object sender, Bitmap image),参数缺少ref引用,需手动修改

利用代码控制绑定事件:

sourcePlayer.NewFrame += new AForge.Controls.VideoSourcePlayer.NewFrameHandler(sourcePlayer_NewFrame);

录制完视频解除绑定:

sourcePlayer.NewFrame -= new AForge.Controls.VideoSourcePlayer.NewFrameHandler(sourcePlayer_NewFrame);

二是VideoCaptureDevice对象的NewFrame事件:void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)

利用代码控制绑定事件:

div.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);

录制完视频解除绑定:

div.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame);

2)在NewFrame事件中,利用VideoFileWriter对象写入视频文件

6.WPF下用到winforms控件标签WindowsFormsHost会遮挡wpf控件显示问题

代替VideoSourcePlayer控件可以使用WPF标准控件Image,在NewFrame事件中,不断刷新Image.Source,因为是跨线程控制Image控件的属性值,

需要利用委托方法的方式刷新Image.Source