Skip to content

Instantly share code, notes, and snippets.

@cjsauer
Last active September 5, 2018 19:58
Show Gist options
  • Save cjsauer/0a360f307a585b5ea3a19def7e6526b9 to your computer and use it in GitHub Desktop.
Save cjsauer/0a360f307a585b5ea3a19def7e6526b9 to your computer and use it in GitHub Desktop.
namespace MyProject.Core
{
using MyProject.Utilities;
using NatCorderU.Core;
using System.Collections;
using UnityEngine;
public class ReplayRecorder : MonoBehaviour
{
public int width = 960;
public int height = 540;
public int framesPerSecond = 30;
public int replayLengthSeconds = 5;
private CircularBuffer<Frame> _buffer;
private bool _isRendering = false;
private IEnumerator Start()
{
// Create the buffer for storing the latest N frames
_buffer = new CircularBuffer<Frame>(framesPerSecond * replayLengthSeconds);
// Start NatCorder
NatCorder.StartRecording(
Container.MP4,
new VideoFormat(width, height, framesPerSecond),
AudioFormat.None,
OnReplay);
// (Temporary) Stop recording after 10 seconds to test out replay
yield return new WaitForSeconds(10f);
RenderReplay();
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (NatCorder.IsRecording && !_isRendering)
{
if (_buffer.IsFull)
{
RenderTexture.ReleaseTemporary(_buffer.Front());
}
var frame = NatCorder.AcquireFrame();
Graphics.Blit(source, frame);
_buffer.PushBack(frame);
}
Graphics.Blit(source, destination);
}
public void RenderReplay()
{
if (NatCorder.IsRecording)
{
_isRendering = true;
for (int i = 0; i < _buffer.Size; i++)
{
var frame = _buffer[i];
NatCorder.CommitFrame(frame);
}
NatCorder.StopRecording();
}
}
void OnReplay(string videoPath)
{
_isRendering = false;
Debug.Log("Video saved to: " + videoPath);
string localURL = "file://" + videoPath;
#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
Handheld.PlayFullScreenMovie(
localURL,
Color.black,
FullScreenMovieControlMode.Full,
FullScreenMovieScalingMode.AspectFit);
#else
Application.OpenURL(localURL);
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment