unity一种视频动态加载方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Video;
using UnityEngine.UI;

public class Download : MonoBehaviour
{
    string urlPath = "http://192.168.0.108/test/end.mp4";//资源网络路径  
    string file_SaveUrl;//资源保路径  
    FileInfo file;
    private bool down;
    public VideoPlayer _videoPlayer;
    private void Awake()
    {
        _videoPlayer = GetComponent<VideoPlayer>();
    }
    private void Start()
    {
        var path = Application.persistentDataPath;
        file_SaveUrl = path + "/end.mp4"; //保存的本地路径    记得加上文件后缀名  
        file = new FileInfo(file_SaveUrl);
        Debug.Log("path:" + file_SaveUrl);
        DirectoryInfo mydir = new DirectoryInfo(file_SaveUrl);
        if (File.Exists(file_SaveUrl))//判断一下本地是否有了该音频  如果有就不需下载  
        {
            PlayVideo();
        }
        else
        {
            StartCoroutine(DownFile(urlPath));
        }
    }
    IEnumerator DownFile(string url)
    {

        WWW www = new WWW(url);
        down = false;
        yield return www;
        down = true;
        if (www.isDone)
        {
            byte[] bytes = www.bytes;
            CreatFile(bytes);
            PlayVideo();
        }
    }
    void CreatFile(byte[] bytes)
    {
        Stream stream;
        stream = file.Create();
        stream.Write(bytes, 0, bytes.Length);
        Debug.Log("下载完成");
        stream.Close();
        stream.Dispose();
    }

    public void PlayVideo()
    {
        StartCoroutine(DelayPlayVideo(1));
    }

    IEnumerator DelayPlayVideo(float time)
    {
        _videoPlayer.source = VideoSource.Url;
        _videoPlayer.url = file_SaveUrl;
        _videoPlayer.Prepare();
        _videoPlayer.playOnAwake = false;
        while (!_videoPlayer.isPrepared)
        {
            Debug.Log("Preparing Video");
            yield return null;
        }
        _videoPlayer.Play();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31967569/article/details/85340889