Unity 使用AVProVideo外掛載入並下載視訊
阿新 • • 發佈:2018-11-11
找了很長時間,關於視訊的下載,總是出現各種問題,現在解決了。
方法一:
這種方法也可以下載視訊,但是有一個問題就是:在視訊播放且下載的時候,就會出現,這個視訊正在播放,但又因為下載,視訊先下載,再播放,這個中間就會出現視訊卡段在某一個畫面中。這樣就有點不太好了,可能這個方法一還有其他程式碼需要穿插,但是我沒有找到,就先捨棄這個方法。
//方法一 System.Net.WebClient myWebClient = new System.Net.WebClient(); myWebClient.DownloadFile(videoURL, path + @"/" + downloadVideoName + ".mp4");
方法二:
WWW類裡面的 LoadFromCacheOrDownload。但是會每次都快取,這個方法不行
WWW www = WWW.LoadFromCacheOrDownload (videoURL,1);
yield return www;
方法三:
用流來解決:
//方法三 WWW www = new WWW(videoURL); yield return www; if (!string.IsNullOrEmpty(www.error)) { print("The request failed"); } else { print("The request is successful"); fs = File.Create(path + "/" + downloadVideoName + ".mp4"); //path為你想儲存檔案的路徑。 fs.Write(www.bytes, 0, www.bytes.Length); fs.Close(); }
介面:
完整程式碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using RenderHeads.Media.AVProVideo; namespace AR.Settings { public class DownVideo : MonoBehaviour { public MediaPlayer itm; FileStream fs; string path; void Awake() { StartCoroutine(DownOrLoadVideo("AAA", "http://kanyikan.oss-cn-shanghai.aliyuncs.com/kanrongmei/%E6%B1%89%E5%85%B3%E7%B4%AB%E7%A0%82.mp4")); } /// <summary> /// 載入視訊並下載 /// </summary> /// <param name="itm">ImgTargetMgr</param> /// <param name="downloadVideoName">識別圖名</param> /// <param name="videoURL">視訊網路地址</param> IEnumerator DownOrLoadVideo(string downloadVideoName, string videoURL) { #if UNITY_EDITOR path = Application.dataPath + @"/Video"; #elif UNITY_IPHONE || UNITY_ANDROID string[] src = new string[1] { "Android" }; string[] srcs = Application.persistentDataPath.Split(src, System.StringSplitOptions.None); path = srcs[0] + @"/Video"; #endif if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //是否下載 if (File.Exists(path + @"/" + downloadVideoName + ".mp4")) { //本地載入 itm.OpenVideoFromFile(MediaPlayer.FileLocation.RelativeToProjectFolder, path + "/" + downloadVideoName + ".mp4", true); } else { //網路載入 itm.OpenVideoFromFile(MediaPlayer.FileLocation.AbsolutePathOrURL, videoURL, true); //方法一 //下載檔案 //System.Net.WebClient myWebClient = new System.Net.WebClient(); //myWebClient.DownloadFile(videoURL, path + @"/" + downloadVideoName + ".mp4"); //方法三 WWW www = new WWW(videoURL); yield return www; if (!string.IsNullOrEmpty(www.error)) { print("The request failed"); } else { print("The request is successful"); fs = File.Create(path + "/" + downloadVideoName + ".mp4"); //path為你想儲存檔案的路徑。 fs.Write(www.bytes, 0, www.bytes.Length); fs.Close(); } Debug.Log("The Video Download successful"); } } } }