gpt4 book ai didi

c# - c#中使用AFORGE录制视频

转载 作者:行者123 更新时间:2023-12-04 23:00:36 25 4
gpt4 key购买 nike

我尝试了以下方法以每秒 25 帧速率从网络摄像头录制视频,持续 10 秒,但是当我得到输出视频时,它是 2 秒,并且与视频流相比,帧的播放速度更快。

代码如下。

    using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Threading;
using AForge.Video.FFMPEG;

namespace AforgeTutorial
{
public partial class Form1 : Form
{
private FilterInfoCollection ListOfCams;
private VideoCaptureDevice SelectedCam; //From where we will take image
System.Timers.Timer tim;

Thread t;
bool isNewFrame = false;
VideoFileWriter writer;

public Form1()
{
InitializeComponent();
tim = new System.Timers.Timer(10000);
tim.Elapsed += new System.Timers.ElapsedEventHandler(tim_Elapsed);
t = new Thread(saveVideo);
}

void tim_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (isRecord)
{
writer.Close();
isRecord = false;
}
}

private void Form1_Load(object sender, EventArgs e)
{
ListOfCams = new FilterInfoCollection(FilterCategory.VideoInputDevice);

if (ListOfCams.Count == 0)
return;

comboBox1.Items.Clear();
foreach (FilterInfo Cam in ListOfCams)
{
comboBox1.Items.Add(Cam.Name);
}
}

private void StopCamera()
{
SelectedCam.SignalToStop();
SelectedCam.Stop();
}

bool isRecord = false;

private void Start_Click(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
return;

SelectedCam = new VideoCaptureDevice(ListOfCams[comboBox1.SelectedIndex].MonikerString);

SelectedCam.NewFrame += new NewFrameEventHandler(SelectedCam_NewFrame);
SelectedCam.Start();
}

Bitmap image;
void SelectedCam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
image = (Bitmap)eventArgs.Frame.Clone();
isNewFrame = true;
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
StopCamera();
}

private void Stop_Click(object sender, EventArgs e)
{
StopCamera();
}

private void btnRecord_Click(object sender, EventArgs e)
{
tim.Start();

if (!isRecord)
{
writer = new VideoFileWriter();
writer.Open(@"C:/code-bude_test_video.mp4", 640, 480, 25, VideoCodec.MPEG4,10000);
}

isRecord = !isRecord;
if (isRecord)
t.Start();
}

void saveVideo()
{
while (isRecord)
{
if (isNewFrame)
{
writer.WriteVideoFrame(image);
isNewFrame = false;
}
}
}
}
}

最佳答案

您的代码中存在多线程问题。您不能像那样写入共享变量并期望它同步。

您有三个线程:用户界面、流式传输和保存。 (SelectedCam_NewFrame 在 AForge 流线程中运行)。列出至少在两个线程(isRecord、isNewFrame 等)中访问的所有变量并添加适当的同步。

您可以在 threading in C# 上查看这个非常好的引用资料.

请注意,即使使用同步,如果您的编写器线程在多个图像到达时很忙,您也可能会丢失帧。您可能想要做的是将相机产生的帧收集到一个队列中,并在写入线程中使用该队列。检查生产者/消费者模式。

关于c# - c#中使用AFORGE录制视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25158542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com