using
AForge.Video;
using
AForge.Video.DirectShow;
using
AForge.Video.FFMPEG;
using
System;
using
System.Drawing;
using
System.Windows.Forms;
namespace
CameraCapture
{
public
partial class Form1 : Form
{
private
FilterInfoCollection filterInfoCollection;
private
VideoCaptureDevice captureDevice;
//AForge.Video.FFMPEG 提供的视频写入类
private
VideoFileWriter videoFileWriter = new
VideoFileWriter();
private
VideoCapabilities[] videoCapabilities;
private
string fileName;
private
Size frameSize;
private
int framRate;
public
Form1()
{
InitializeComponent();
filterInfoCollection = new
FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach
(FilterInfo item in
filterInfoCollection)
{
this .comboBox1.Items.Add(item.Name);
}
this .comboBox1.SelectedIndex = 0;
//先初始化一下 否则在下面判断是否已运行时会报错
captureDevice = new
VideoCaptureDevice();
}
private
void button1_Click( object
sender, EventArgs e)
{
if
( this .checkBox1.Checked)
{
SaveFileDialog sfd = new
SaveFileDialog();
sfd.AddExtension = true ;
sfd.DefaultExt = ".avi" ;
sfd.Filter = "视频文件|*.avi" ;
if
(sfd.ShowDialog() == DialogResult.OK)
{
fileName = sfd.FileName;
}
//文件名 宽度 高度 帧率 编码
videoFileWriter.Open(fileName, frameSize.Width, frameSize.Height, framRate, VideoCodec.MPEG4);
}
if
(captureDevice.IsRunning)
captureDevice.Stop();
captureDevice.NewFrame += captureDevice_NewFrame;
captureDevice.Start();
MessageBox.Show(videoFileWriter.FrameRate.ToString());
}
private
void captureDevice_NewFrame( object
sender, NewFrameEventArgs eventArgs)
{
this .pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
if
( this .checkBox1.Checked)
{
videoFileWriter.WriteVideoFrame((Bitmap)eventArgs.Frame);
}
}
private
void comboBox1_SelectedIndexChanged( object
sender, EventArgs e)
{
GetVideoCapabilities();
}
/// <summary>
///获取摄像头分辨率
/// </summary>
private
void GetVideoCapabilities()
{
captureDevice = new
VideoCaptureDevice(filterInfoCollection[comboBox1.SelectedIndex].MonikerString);
try
{
videoCapabilities = captureDevice.VideoCapabilities;
foreach
(VideoCapabilities capabilty in
videoCapabilities)
{
if
(! this .comboBox2.Items.Contains(capabilty.FrameSize))
{
this .comboBox2.Items.Add(capabilty.FrameSize);
}
}
if
(videoCapabilities.Length == 0)
{
this .comboBox2.Items.Add( "Not supported" );
}
this .comboBox2.SelectedIndex = 0;
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private
void comboBox2_SelectedIndexChanged( object
sender, EventArgs e)
{
this .frameSize = captureDevice.VideoCapabilities[comboBox2.SelectedIndex].FrameSize;
this .framRate = captureDevice.VideoCapabilities[comboBox2.SelectedIndex].FrameRate;
}
/// <summary>
/// 关闭后结束捕获 释放资源
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private
void Form1_FormClosing( object
sender, FormClosingEventArgs e)
{
if
(captureDevice.IsRunning)
{
captureDevice.Stop();
}
if
(videoFileWriter.IsOpen)
{
videoFileWriter.Close();
}
}
}
}
|