GetVideoImage.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. using UnityEngine.UI;
  8. public class GetVideoImage : MonoBehaviour
  9. {
  10. public string url;
  11. RawImage rawImage;
  12. MeshRenderer render;
  13. AVProVideoPlayer ap;
  14. string localpath;
  15. private void OnEnable()
  16. {
  17. if (localpath != "" && localpath != null)
  18. {
  19. if (File.Exists(localpath))
  20. {
  21. this.GetComponent<AVProVideoPlayer>().SetUrl(localpath);
  22. this.GetComponent<AVProVideoPlayer>().Play();
  23. }
  24. }
  25. }
  26. private void Start()
  27. {
  28. localpath = Application.persistentDataPath + "/OOBE/" + url.Split('/')[url.Split('/').Length-1];
  29. ap = this.GetComponent<AVProVideoPlayer>();
  30. rawImage = this.GetComponent<RawImage>();
  31. render = this.GetComponent<MeshRenderer>();
  32. if(!File.Exists(localpath))
  33. {
  34. if(!Directory.Exists(Application.persistentDataPath + "/OOBE"))
  35. Directory.CreateDirectory(Application.persistentDataPath + "/OOBE");
  36. OnDownloadAssets();
  37. }
  38. }
  39. private void OnDownloadAssets()//下载资源
  40. {
  41. StartCoroutine(DownloadFormServer_IE(url));
  42. }
  43. //其他方法
  44. private IEnumerator DownloadFormServer_IE(string url)//从服务器下载资源
  45. {
  46. Debug.Log("正在下载" + url);
  47. UnityWebRequest request = UnityWebRequest.Get(url);
  48. //直接下载不显示进度
  49. yield return request.SendWebRequest();
  50. if (request.result == UnityWebRequest.Result.ProtocolError || request.result == UnityWebRequest.Result.ConnectionError)
  51. {
  52. yield break;
  53. }
  54. DownloadHandler downloadHandler = request.downloadHandler;
  55. if (!downloadHandler.isDone)
  56. {
  57. Debug.Log("正在下载");
  58. yield return downloadHandler;
  59. }
  60. else
  61. {
  62. Debug.Log("下载完成");
  63. byte[] data = request.downloadHandler.data;
  64. using (FileStream fs = new FileStream(localpath, FileMode.Create))
  65. {
  66. fs.Write(data, 0, data.Length);
  67. fs.Close();
  68. if (localpath != "" && localpath != null)
  69. {
  70. if (File.Exists(localpath))
  71. {
  72. this.GetComponent<AVProVideoPlayer>().SetUrl(localpath);
  73. this.GetComponent<AVProVideoPlayer>().Play();
  74. }
  75. }
  76. }
  77. }
  78. }
  79. // Update is called once per frame
  80. void Update()
  81. {
  82. if (rawImage)
  83. {
  84. rawImage.texture = ap.getTexture();
  85. }
  86. if (render)
  87. {
  88. render.material.mainTexture = ap.getTexture();
  89. }
  90. }
  91. private void OnDisable()
  92. {
  93. this.GetComponent<AVProVideoPlayer>().Pause();
  94. }
  95. }