C#实现摄像头视频录制与保存

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
相关推荐
YuanlongWang3 小时前
C# 设计模式——观察者
windows·设计模式·c#
数据科学作家3 小时前
如何入门python机器学习?金融从业人员如何快速学习Python、机器学习?机器学习、数据科学如何进阶成为大神?
大数据·开发语言·人工智能·python·机器学习·数据分析·统计分析
孤客网络科技工作室3 小时前
Python - 100天从新手到大师:第五十八天 Python中的并发编程(1-3)
开发语言·python
Coovally AI模型快速验证3 小时前
突破性开源模型DepthLM问世:视觉语言模型首次实现精准三维空间理解
人工智能·语言模型·自然语言处理·ocr·音视频·ai编程
go_bai4 小时前
Linux_基础IO(2)
linux·开发语言·经验分享·笔记·学习方法·1024程序员节
不会算法的小灰4 小时前
JavaScript基础详解
开发语言·javascript·udp
杨福瑞4 小时前
数据结构:顺序表讲解(2)
c语言·开发语言·数据结构
爬虫程序猿8 小时前
用 Python 给京东商品详情做“全身 CT”——可量产、可扩展的爬虫实战
开发语言·爬虫·python
徐同保10 小时前
tailwindcss暗色主题切换
开发语言·前端·javascript