UnityVideoPlayer远程下载调试

2023/06 13 19:06

可以反复下载指定的视频并播放,测试视频播放的兼容性

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;

[RequireComponent(typeof(UnityEngine.Video.VideoPlayer))]
[RequireComponent(typeof(UnityEngine.UI.RawImage))]
public class MyVideoPlayer : MonoBehaviour
{
    private RenderTexture mRenderTexture;

#if UNITY_ANDROID
    const float GUIScale = 3;
#else
    const float GUIScale = 1;
#endif

    private GUILayoutOption[] InputBoxStyle  = new GUILayoutOption[] { GUILayout.MaxWidth(500 * GUIScale), GUILayout.MaxHeight(40* GUIScale) };
    private GUILayoutOption[] SliderBoxStyle = new GUILayoutOption[] { GUILayout.MaxWidth(500 * GUIScale), GUILayout.MaxHeight(40* GUIScale) };
    private GUILayoutOption[] ButtonStyle    = new GUILayoutOption[] { GUILayout.MaxWidth(200 * GUIScale), GUILayout.MaxHeight(40* GUIScale) };

    private string mServerUrl = "http://192.168.3.23/";
    private int mFilename = 1;

    private IEnumerator mDownloadTask;
    private string mProgressLabel = string.Empty;
    private Dictionary<string, string> mDownloadFiles = new Dictionary<string, string>();
    private GUISkin mGUISkin;
    void OnGUI()
    {
        GUILayout.BeginVertical();

        mServerUrl = GUILayout.TextArea(mServerUrl, InputBoxStyle);

        mFilename = (int)GUILayout.HorizontalSlider(mFilename, 1, 20, SliderBoxStyle);

        var mPlayerUrl = mServerUrl + mFilename.ToString() + ".mp4";
        GUILayout.Label(mPlayerUrl);

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("下载", ButtonStyle))
        {
            if (mDownloadFiles.TryGetValue(mPlayerUrl, out var localFilename))
            {
                ShowTips($"{mPlayerUrl} 文件已下载 {localFilename}");
            }
            else
            {
                if (mDownloadTask != null)
                {
                    StopCoroutine(mDownloadTask);
                    mDownloadTask = null;
                }
                mDownloadTask = DownloadWebFile(mPlayerUrl);
                StartCoroutine(mDownloadTask);
            }
        }
        if (GUILayout.Button("播放", ButtonStyle))
        {
            if (mDownloadFiles.TryGetValue(mPlayerUrl, out var localFilename))
            {
                PlayByUrl(localFilename);
            }
            else
            {
                ShowTips($"{mPlayerUrl} 文件未下载");
            }
        }
        GUILayout.EndHorizontal();

        if (mProgressLabel.Length > 0)
        {
            GUILayout.Label(mProgressLabel);
        }

        GUILayout.EndVertical();
    }

    void ShowTips(string tips)
    {
        mProgressLabel = tips;
    }

    IEnumerator DownloadWebFile(string remoteUrl)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(remoteUrl);

        Debug.Log($"DownloadStart: {remoteUrl}");
        ShowTips($"DownloadStart: {remoteUrl} ");

        unityWebRequest.SendWebRequest();

        for(int i=0; i<1024*1024; ++i)
        {
            ShowTips($"DownloadProgress: {unityWebRequest.downloadProgress} {remoteUrl} ");
            yield return null;

            if (unityWebRequest.isDone && unityWebRequest.result == UnityEngine.Networking.UnityWebRequest.Result.Success)
            {
                break;
            }
        }

        Debug.Log($"DownloadFinish: {remoteUrl}");
        ShowTips($"DownloadFinish: {remoteUrl} ");

        var downloadHandler=unityWebRequest.downloadHandler;

        var localFilename = System.IO.Path.Combine(Application.persistentDataPath, $"{DateTime.Now.Ticks}.mp4").Replace("\\", "/");
        System.IO.File.WriteAllBytes(localFilename, downloadHandler.data);

        mDownloadFiles[remoteUrl] = localFilename;
    }

    void PlayByUrl(string localFilename)
    {
        var videoPlayer = this.GetComponent<UnityEngine.Video.VideoPlayer>();
        if (videoPlayer != null)
        {
            videoPlayer.Stop();

            videoPlayer.source = UnityEngine.Video.VideoSource.Url;
            videoPlayer.url = localFilename;
            videoPlayer.isLooping = true;

            Debug.Log($"Play:{localFilename}");
            ShowTips($"Play:{localFilename} ");

            videoPlayer.Play();
        }
    }

    void Start()
    {
        var videoPlayer = this.GetComponent<UnityEngine.Video.VideoPlayer>();
        var rawImage = this.GetComponent<UnityEngine.UI.RawImage>();
        if (rawImage != null && videoPlayer != null)
        {
            videoPlayer.errorReceived += OnError;

            var videoWidth = 1136;
            var videoHeight = 640;

            if (mRenderTexture == null)
            {
                mRenderTexture = RenderTexture.GetTemporary(videoWidth, videoHeight);
            }

            if (mRenderTexture != null)
            {
                videoPlayer.targetTexture = mRenderTexture;
                rawImage.texture = mRenderTexture;
            }
        }
    }

    void OnError(UnityEngine.Video.VideoPlayer source, string msg)
    {
        Debug.LogError($"[ERROR] {source.name} {msg}");
        source.Stop();
    }
}