找了很长时间,关于视频的下载,总是出现各种问题,现在解决了。
方法一:
这种方法也可以下载视频,但是有一个问题就是:在视频播放且下载的时候,就会出现,这个视频正在播放,但又因为下载,视频先下载,再播放,这个中间就会出现视频卡段在某一个画面中。这样就有点不太好了,可能这个方法一还有其他代码需要穿插,但是我没有找到,就先舍弃这个方法。
//方法一
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");
}
}
}
}