C#实现摄像头视频录制与保存,包含系统原生API和第三方库两种实现方式
一、使用Windows Media Capture API(原生方案)
csharp
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using System.Threading.Tasks;
public class VideoRecorder
{
private MediaCapture _mediaCapture;
private StorageFile _outputFile;
private bool _isRecording = false;
// 初始化摄像头
public async Task InitializeAsync()
{
_mediaCapture = new MediaCapture();
var settings = new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video
};
await _mediaCapture.InitializeAsync(settings);
}
// 开始录制
public async Task StartRecordingAsync(string fileName)
{
if (_isRecording) return;
_outputFile = await KnownFolders.VideosLibrary.CreateFileAsync(
fileName, CreationCollisionOption.GenerateUniqueName);
var encodingProfile = MediaEncodingProfile.CreateMp4(
VideoEncodingQuality.Auto);
await _mediaCapture.StartRecordToStorageFileAsync(
encodingProfile, _outputFile);
_isRecording = true;
}
// 停止录制
public async Task StopRecordingAsync()
{
if (!_isRecording) return;
await _mediaCapture.StopRecordAsync();
_isRecording = false;
_mediaCapture.Dispose();
}
}
// 使用示例
var recorder = new VideoRecorder();
await recorder.InitializeAsync();
await recorder.StartRecordingAsync("my_video.mp4");
// 执行其他操作...
await recorder.StopRecordingAsync();
二、使用AForge.NET第三方库
csharp
using AForge.Video;
using AForge.Video.DirectShow;
using System.Drawing;
using System.IO;
public class AForgeRecorder
{
private VideoCaptureDevice _videoSource;
private AVIWriter _aviWriter;
private bool _isRecording = false;
// 初始化摄像头
public void Initialize()
{
FilterInfoCollection devices = new FilterInfoCollection(
FilterCategory.VideoInputDevice);
if (devices.Count == 0)
throw new Exception("未检测到摄像头设备");
_videoSource = new VideoCaptureDevice(devices[0].MonikerString);
_videoSource.VideoResolution =
_videoSource.VideoCapabilities[0]; // 选择最高分辨率
}
// 开始录制
public void StartRecording(string fileName)
{
_aviWriter = new AVIWriter("WMV",
_videoSource.VideoResolution.FrameWidth,
_videoSource.VideoResolution.FrameHeight);
_videoSource.NewFrame += (sender, e) =>
{
_aviWriter.WriteVideoFrame(e.Frame);
};
_videoSource.Start();
_isRecording = true;
}
// 停止录制
public void StopRecording()
{
if (!_isRecording) return;
_videoSource.SignalToStop();
_aviWriter.Close();
_isRecording = false;
}
}
// 使用示例
var recorder = new AForgeRecorder();
recorder.Initialize();
recorder.StartRecording("recorded_video.avi");
// 执行其他操作...
recorder.StopRecording();
三、关键参数配置
| 参数项 | 原生方案配置方法 | AForge方案配置方法 |
|---|---|---|
| 视频分辨率 | MediaCaptureInitializationSettings中的VideoDeviceController |
VideoCaptureDevice.VideoResolution |
| 帧率 | MediaCaptureInitializationSettings中的MaxFrameRate |
VideoCaptureDevice.DefaultFrameRate |
| 编码格式 | MediaEncodingProfile指定视频编码类型 |
AVIWriter构造函数指定编码格式 |
| 保存路径 | KnownFolders指定系统文件夹 |
自定义文件路径 |
四、高级功能实现
1. 实时预览窗口
csharp
// 原生方案预览
public async Task StartPreviewAsync()
{
var previewWindow = new CaptureElement();
previewWindow.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
}
// AForge方案预览
public void StartPreview(Control control)
{
control.Controls.Add(new PictureBox {
Image = _videoSource.GetCurrentVideoFrame(),
Dock = DockStyle.Fill
});
}
2. 视频压缩设置
csharp
// 原生方案H.264压缩
var profile = MediaEncodingProfile.CreateMp4(
VideoEncodingQuality.Highest);
profile.Video.Codec = VideoCodec.H264;
// AForge方案调整码率
AVIWriter writer = new AVIWriter("WMV", width, height);
writer.VideoStreamInfo.Bitrate = 2000000; // 2Mbps
五、异常处理与资源管理
csharp
public class SafeRecorder : IDisposable
{
private bool _disposed = false;
// 原生方案资源释放
public void Dispose()
{
if (!_disposed)
{
_mediaCapture?.Dispose();
_disposed = true;
}
}
// AForge方案资源释放
public void SafeStop()
{
try
{
_videoSource?.SignalToStop();
_aviWriter?.Close();
}
catch (Exception ex)
{
// 记录日志
}
}
}
参考代码 c#调用本地摄像头录制视频并保存 www.youwenfan.com/contentcsj/59163.html
六、完整项目结构
VideoRecorderApp/
├── src/
│ ├── VideoRecorder.sln
│ ├── NativeRecorder/ (原生方案实现)
│ │ ├── MainPage.xaml
│ │ └── VideoService.cs
│ └── AForgeRecorder/ (第三方方案实现)
│ ├── RecorderForm.cs
│ └── VideoProcessor.cs
├── assets/
│ └── default_icon.png
└── docs/
└── 开发指南.md