using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using UnityEngine.Video;
public class DownloadManager : MonoBehaviour
{
private string UrlPath = ;//地址
public List<string> Meditallist = new List<string>();
private string MusicFile = Application.streamingAssetsPath + "/MusicList/";//音频文件夹
private string VideoFile = Application.streamingAssetsPath + "/VideoList/";//视频文件夹
public AudioSource audiosoure;
public int numDownloaded = 0; // 下载完成的视频数量
private void Start()
{
// 遍历 MeditalDic 中的所有元素,将视频名称添加到 Meditallist 列表中
for (int i = 1; i < LModelList.instance.MeditalDic.Count + 1; i++)
{
LModelList.instance.MeditalDic.TryGetValue(i, out string value);
string[] s = value.Split('\t');
Meditallist.Add(s[1]);
Meditallist.Add(s[2]);
Meditallist.Add(s[3]);
}
// 移除 Meditallist 中所有为 null 或空字符串的元素
Meditallist.RemoveAll(string.IsNullOrEmpty);
StartCoroutine(DownloadAllAssets());
}
IEnumerator DownloadAllAssets()
{
// 遍历 Meditallist 中的所有视频名称,检查其是否已经存在于本地文件夹中,若不存在则启动下载协程
for (int i = 0; i < Meditallist.Count; i++)
{
string FileName = Meditallist[i];
string FilePath = GetFilePath(FileName) + Meditallist[i];
if (File.Exists(FilePath))
{
Debug.Log("Video file already exists at " + FilePath);
continue;
}
yield return StartCoroutine(DownLoadAssets(UrlPath + FileName, FilePath)); // 启动下载协程
numDownloaded++;
}
if(numDownloaded>= Meditallist.Count)
{
Debug.Log("下载完成");
}
}
IEnumerator DownLoadAssets(string urlpath,string filepath)
{
UnityWebRequest req = UnityWebRequest.Get(urlpath);
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success) // 如果下载请求失败
{
Debug.LogError("Failed to download video: " + req.error + " urlpath: " + urlpath); // 输出错误信息
yield break; // 终止协程
}
byte[] bytes = req.downloadHandler.data; // 从UnityWebRequest对象中获取下载的视频的二进制数据
using (FileStream fs = new FileStream(filepath, FileMode.Create)) // 创建一个FileStream对象,并将视频数据写入本地文件中
{
fs.Write(bytes, 0, bytes.Length); // 将视频二进制数据写入文件流
}
// Debug.Log("Video downloaded to " + filepath); // 输出下载完成信息
}
string GetFilePath(string filetype)//方法返回文件的完整路径,通过调用GetFolderName()方法获取文件所在的文件夹路径。
{
string FolderName = GetFolderName(filetype);
return FolderName;
}
string GetFolderName(string FileName)//方法根据文件名中的最后两个字符判断文件属于哪个文件夹,如果是以"导语"或"音效"结尾的文件,则归入音频文件夹MusicFile;否则归入视频文件夹VideoFile。函数返回所属文件夹的路径。
{
string lastTwo = (FileName.Length>2)?FileName.Substring(FileName.Length - 2):FileName;
if (lastTwo == "导语" ||lastTwo== "音效")
{
return MusicFile;
}
else
{
return VideoFile;
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
ResMusic();
}
public void ResMusic()
{
AssetBundle ab = AssetBundle.LoadFromFile(MusicFile+"花海");
VideoClip vc = ab.LoadAsset<VideoClip>("花海");
this.gameObject.GetComponent<VideoPlayer>().clip = vc;
ab.Unload(false);
}
}
01-05
09-20
5502
06-05
06-05