在网上看了很多关于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;
}
}
}
}