Unity使用FFmpeg在游戏中录屏

在网上看了很多关于ffmpeg的教程,写法也很多,和其他插件结合的也很多,搞得我这个初学者云里雾里,经过一天的误打误撞,让我成功了,下面分享我的代码,只用了FFmpeg一个插件。

unity使用FFmpeg实现在游戏中录屏啊啊啊成功了!!激动!

我是写了两个按钮来出发开始录屏和结束录屏的

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
public class InstanceVideoController : MonoBehaviour
{
    string ffmpegPath = "F:/test/Camera/Assets/StreamingAssets/ffmpeg/ffmpeg.exe"; // 指定 FFmpeg 可执行文件的路径
    string outputFolder; // 输出文件夹路径
    private Process ffmpegProcess;
    public Button OpenButton, CloseButton;
    public void Start()
    {
        outputFolder = Application.streamingAssetsPath + "/Video/capture.mp4";//视频的输出路径
        OpenButton.onClick.AddListener(StartRecording);
        CloseButton.onClick.AddListener(StopRecording);
    }
    // 开始录制
    public void StartRecording()
    {

        if (ffmpegProcess == null || ffmpegProcess.HasExited)
        {
            string arguments = $"-y -f gdigrab -r 30 -s {Screen.width}x{Screen.height} -i desktop -c:v libx264 -preset ultrafast -crf 28 -pix_fmt yuv420p \"{outputFolder}\"";
            ffmpegProcess = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = ffmpegPath,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                }
            };

            ffmpegProcess.Start();
            UnityEngine.Debug.Log("开始录制...");

        }
    }

    // 结束录制
    public void StopRecording()
    {
        //UnityEngine.Debug.Log("结束录制1");
        if (ffmpegProcess != null && !ffmpegProcess.HasExited)
        {
            ffmpegProcess.StandardInput.WriteLine("q");
            UnityEngine.Debug.Log("结束录制中...");
            ffmpegProcess.WaitForExit(2000);//等待两秒后
            if (ffmpegProcess != null)
            {
                UnityEngine.Debug.Log("正常结束录制");

                ffmpegProcess = null;
            }

        }
    }
}

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值