using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Video;
public class VideoThumbGetter
{
private Texture2D t2d;
private bool isLoadFinish;
private bool isLoadSuc;
public IEnumerator GetThumb(string videoUrl, UnityAction<Texture2D, bool> completed)
{
var videoPlayer = new GameObject().AddComponent<VideoPlayer>();
videoPlayer.url = videoUrl;
videoPlayer.sendFrameReadyEvents = true;
videoPlayer.frameReady += onFrameReady;
videoPlayer.errorReceived += onVideoError;
videoPlayer.Play();
yield return new WaitUntil(() => isLoadFinish);
//if (isLoadSuc)
// t2d.Compress(true);
completed(t2d, isLoadSuc);
Object.Destroy(videoPlayer.gameObject);
}
private void onVideoError(VideoPlayer source, string message)
{
Debug.Log("Unity不支持该视频" + source.url);
t2d = new Texture2D(2, 2);
source.sendFrameReadyEvents = false;
source.frameReady -= onFrameReady;
source.errorReceived -= onVideoError;
isLoadSuc = false;
isLoadFinish = true;
}
private void onFrameReady(VideoPlayer source, long frameIdx)
{
if (frameIdx == 0)
{
RenderTexture renderTexture = source.texture as RenderTexture;
try
{
t2d = ScaleTexture(renderTexture, GetScaleFactor(renderTexture.width, renderTexture.height));
isLoadSuc = true;
}
catch
{
t2d = new Texture2D(2, 2);
isLoadSuc = false;
}
source.sendFrameReadyEvents = false;
source.frameReady -= onFrameReady;
source.errorReceived -= onVideoError;
isLoadFinish = true;
}
}
/// <summary>
/// 将照片缩放到小尺寸时的“缩放倍数”
/// </summary>
/// <param name="originalWidth">照片原始尺寸(宽)</param>
/// <param name="originalHeight">照片原始尺寸(高)</param>
/// <param name="maxSize">限制到最大的尺寸</param>
/// <returns>缩放倍数</returns>
private static float GetScaleFactor(int originalWidth, int originalHeight, int maxSize = 256)
{
// 计算宽和高的缩放倍数
float widthScale = (float)maxSize / originalWidth;
float heightScale = (float)maxSize / originalHeight;
// 返回较小的那个缩放倍数,以确保最终尺寸不会超过最大限制尺寸
return Mathf.Min(widthScale, heightScale);
}
//根据渲染贴图、缩放倍数 生成视频缩略图
private static Texture2D ScaleTexture(RenderTexture source, float scale)
{
// 计算缩放后的宽高
int width = (int)(source.width * scale);
int height = (int)(source.height * scale);
// 创建一个新的RenderTexture,用于存储缩放后的结果
RenderTexture scaled = RenderTexture.GetTemporary(width, height);
// 激活新的RenderTexture
RenderTexture.active = scaled;
// 将源RenderTexture绘制到新的RenderTexture上,实现缩放
Graphics.Blit(source, scaled);
// 创建一个新的Texture2D,用于存储最终结果
Texture2D result = new Texture2D(width, height);
// 读取RenderTexture的像素数据到Texture2D中
result.ReadPixels(new Rect(0, 0, width, height), 0, 0);
result.Apply();
RenderTexture.active = null;
// 释放临时的RenderTexture
RenderTexture.ReleaseTemporary(scaled);
// 返回缩放后的Texture2D
return result;
}
}
示例:
private IEnumerator Start()
{
string videoURL = "";
yield return new VideoThumbGetter().GetThumb(videoURL, (t2d, isSuc) =>
{
if (isSuc)//加载成功
{
//处理 t2d
}
else//加载失败
{
}
});
}