脚本MyVideoWriter.cs
using UnityEngine; using System.Collections; using OpenCvSharp; using OpenCvSharp.CPlusPlus; using System.IO; /*author:bluebeandate:2016.8.8all rights reserved*/ public class MyVideoWriter : MonoBehaviour { VideoWriter writer; int w = 0; int h = 0; //VideoWriter参数 string fileName ; FourCC fourcc = FourCC.XVID; double fps = 50; Size size; bool isWriting = false; Texture2D img; // Use this for initialization void Start () { w = Screen.width; h = Screen.height; Size size = new Size(w, h); fileName = Application.streamingAssetsPath + "/output.avi"; img = new Texture2D(w, h,TextureFormat.RGB24,false,false); writer = new VideoWriter(); writer.Open(fileName, fourcc, fps, size, true); } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.S)) { isWriting = !isWriting; } if (isWriting) { StartCoroutine(startWriteVideo()); } } IEnumerator startWriteVideo() { Debug.Log("start write"); while (isWriting) { yield return new WaitForEndOfFrame(); img.ReadPixels(new UnityEngine.Rect(0, 0, w, h), 0, 0, true);//read pixels from screen to texture img.Apply(); Mat tmp = new Mat(h, w, MatType.CV_8UC3, img.GetRawTextureData()); Cv2.CvtColor(tmp, tmp, ColorConversion.BgrToRgb); Cv2.Flip(tmp, tmp, FlipMode.X); writer.Write(tmp); } Debug.Log("end write"); yield return null; } void OnDestroy() { writer.Release(); } }
将脚本拖给摄像机或任何物体,按S键开始录制,再按一次结束录制,关闭程序后,可以查看保存下来的游戏视频。
注意:保存下来的只有视频而没有音频,opencv是一个机器视觉库,为了精简起见,没有提供音频有关的操作。
时间: 2024-10-24 05:54:04