当前位置: 移动技术网 > IT编程>开发语言>c# > C#调用AForge实现摄像头录像的示例代码

C#调用AForge实现摄像头录像的示例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论

1:首先下载

也可以

下载本教程全代码>>

输出为mp4需要用到ffmpeg相关的文件,我打包的库已经带了,去官网找的库可以在这个目录找到:

2:添加这些引用:

3:两个全局变量:

//用来操作摄像头
 private videocapturedevice camera = null;
 //用来把每一帧图像编码到视频文件
 private videofilewriter videooutput = new videofilewriter();


 开始代码:
 //获取摄像头列表
var devs = new filterinfocollection(filtercategory.videoinputdevice);

//实例化设备控制类(我选了第1个)
camera = new videocapturedevice(devs[0].monikerstring);

//配置录像参数(宽,高,帧率,比特率等参数)videocapabilities这个属性会返回摄像头支持哪些配置,从这里面选一个赋值接即可,我选了第1个
camera.videoresolution = camera.videocapabilities[0];

//设置回调,aforge会不断从这个回调推出图像数据
camera.newframe += camera_newframe;

//打开摄像头
camera.start();

//打开录像文件(如果没有则创建,如果有也会清空),这里还有关于
videooutput.open("e:/video.mp4", 
    camera.videoresolution.framesize.width, 
    camera.videoresolution.framesize.height, 
    camera.videoresolution.averageframerate, 
    videocodec.mpeg4, 
    camera.videoresolution.bitcount);
给aforge输出图像数据的回调方法:
//图像缓存
private bitmap bmp = new bitmap(1, 1);

//摄像头输出回调
private void camera_newframe(object sender, newframeeventargs eventargs)
{
 //写到文件
 videooutput.writevideoframe(eventargs.frame);
 lock (bmp)
 {
  //释放上一个缓存
  bmp.dispose();
  //保存一份缓存
  bmp = eventargs.frame.clone() as bitmap;
 }
}

结束代码:

   //停摄像头
   camera.stop();

   //关闭录像文件,如果忘了不关闭,将会得到一个损坏的文件,无法播放
   videooutput.close();

4:修改app.config,兼容net2.0的一些东西:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <startup uselegacyv2runtimeactivationpolicy="true">
 <supportedruntime version="v4.0" sku=".netframework,version=v4.5"/>
 </startup>
 <supportedruntime version="v2.0.50727"/>
</configuration>

不然会这样:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网