VideoSourcePlayer(來自 AForge.Controls)作為預覽畫面。

private FilterInfoCollection videoDevices;
private void Form1_Load(object sender, EventArgs e) {
try {
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0) throw new ApplicationException();
foreach (FilterInfo dev in videoDevices)
tscbxCameras.Items.Add(dev.Name);
tscbxCameras.SelectedIndex = 0;
} catch {
tscbxCameras.Items.Add("No local capture devices");
videoDevices = null;
}
}
private void CameraConn() {
var videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
videoSource.DesiredFrameSize = new Size(320, 240);
videoSource.DesiredFrameRate = 15;
videoSourcePlayer.VideoSource = videoSource;
videoSourcePlayer.Start();
}
private void btnClose_Click(object sender, EventArgs e) {
videoSourcePlayer.SignalToStop();
videoSourcePlayer.WaitForStop();
}
private void Photograph_Click(object sender, EventArgs e) {
try {
if (videoSourcePlayer.IsRunning) {
var bitmap = videoSourcePlayer.GetCurrentVideoFrame();
string path = GetImagePath() + "\\xiaosy.jpg";
if (File.Exists(path)) File.Delete(path);
bitmap.Save(path, ImageFormat.Jpeg); // 直接用 GDI+ 儲存
// 關閉裝置並關閉視窗
videoSourcePlayer.SignalToStop();
videoSourcePlayer.WaitForStop();
this.Close();
}
} catch (Exception ex) {
MessageBox.Show("攝像頭異常:" + ex.Message);
}
}
private string GetImagePath() {
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PersonImg");
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
return dir;
}
引用 AForge.Video.FFMPEG,使用 VideoFileWriter 在 `NewFrame` 事件中寫入幀,停止時呼叫 `Close()`。下一篇將補充完整錄影範例。