首页 > 解决方案 > C#如何创建内存中的视频块

问题描述

我需要录制屏幕,并且在单击按钮等事件时,它应该保存最后 60 秒的录制。

我知道如何截取屏幕截图,但在将图像转换为视频时遇到问题。我想保存最终的视频文件,其他一切都应该在内存操作中。

目前,我将捕获的图像以 JPEG 格式保存到内存流中,当事件触发时,我将图像转换为视频文件。但是有三重转换:Bitmap[] -> JPEG[] -> Bitmap[] -> Video. 这似乎无效。

当我用谷歌搜索时,我只发现如何将视频文件保存到文件系统。例如 Accord 库有VideoFileWritter(例如版本 3.8.2 alpha)

Bitmap bitmap; //bitmap object with screenshot
List<byte[]> data = new List<byte[]>();

// fill data with JPEG images (called periodically)
using (var ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    data.Add(ms.GetBuffer());
}


// create video file (called on demand)
using (VideoFileWriter videoWriter = new VideoFileWriter())
{
    videoWriter.BitRate = videoBitRate;
    videoWriter.FrameRate = Settings.CurrentFramesPerSeconds;
    videoWriter.Width = 1920;
    videoWriter.Height = 1080;
    videoWriter.VideoCodec = VideoCodec.H264;
    videoWriter.VideoOptions["crf"] = "18"; // visually lossless
    videoWriter.VideoOptions["preset"] = "veryfast";
    videoWriter.VideoOptions["tune"] = "zerolatency";
    videoWriter.VideoOptions["x264opts"] = "no-mbtree:sliced-threads:sync-lookahead=0";
            
    videoWriter.Open(Path.Combine(dirName, "output.avi"));
    foreach (var frame in data)
    {
        using (var bmpStream = new MemoryStream(frame))
        using (var img = Image.FromStream(bmpStream))
        using (var bmp = new Bitmap(img))
            videoWriter.WriteVideoFrame(bmp);
    }
}

如何在内存中创建视频块?我想它应该是 CPU 和内存比我目前的解决方案更有效。

或者有没有更有效的方法来记录屏幕的最后几秒钟而不使用文件系统?

我不想使用文件系统,因为计算机中只安装了 ssd。

标签: c#winformsvideoscreenshot

解决方案


推荐阅读