Version: 2022.1
LanguageEnglish
  • C#

MediaEncoder

class in UnityEditor.Media

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

Encodes images and audio samples into an audio or movie file.

Constructing an instance of this class creates an encoder that will create an audio, video or audio/video file with the specified tracks in it.

Call the AddFrame() and AddSamples() methods alternately for each track, so that frames and samples keep each track equally filled.

Once all the wanted frames and samples are added to the file, call Dispose() to end each track properly and close the file.

using UnityEditor.Media;
using UnityEngine;
using Unity.Collections;
using System.IO;

public class Recorder { static public void RecordMovie() { var videoAttr = new VideoTrackAttributes { frameRate = new MediaRational(50), width = 320, height = 200, includeAlpha = false };

var audioAttr = new AudioTrackAttributes { sampleRate = new MediaRational(48000), channelCount = 2, language = "fr" };

int sampleFramesPerVideoFrame = audioAttr.channelCount * audioAttr.sampleRate.numerator / videoAttr.frameRate.numerator;

var encodedFilePath = Path.Combine(Path.GetTempPath(), "my_movie.mp4");

Texture2D tex = new Texture2D((int)videoAttr.width, (int)videoAttr.height, TextureFormat.RGBA32, false);

using (var encoder = new MediaEncoder(encodedFilePath, videoAttr, audioAttr)) using (var audioBuffer = new NativeArray<float>(sampleFramesPerVideoFrame, Allocator.Temp)) { for (int i = 0; i < 100; ++i) { // Fill 'tex' with the video content to be encoded into the file for this frame. // ... encoder.AddFrame(tex);

// Fill 'audioBuffer' with the audio content to be encoded into the file for this frame. // ... encoder.AddSamples(audioBuffer); } } } }

Constructors

MediaEncoderCreate a new encoder with various track arrangements.

Public Methods

AddFrameAppends a frame to the file's video track.
AddSamplesAppends sample frames to the specified audio track.
DisposeFinishes writing all tracks and closes the file being written.