Unity内播放网络或者本地视频(非工程文件内)

且行且珍惜
Unity摊
下午好, 各位! 今天给大家分享Unity内播放网络或者本地视频(本地视频并非工程文件夹中的视频).
我将电脑作为服务器, 在Unity中下载我的电脑上的视频进行播放.
当然对于网络视频也是可行的.

1.环境搭建

在场景中创建Plane,添加AudioSource组件和Play脚本.并创建Resources文件夹.

2.编写脚本

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

public class Play : MonoBehaviour
{

    //本地服务器视频路径(你可以替换成网路视频路径)
    string url = "http://127.0.0.1/video.mp4";
    //下载文件存储路径
    string m_filePath;
    //视频纹理
    MovieTexture movie;
    //声音组件
    AudioSource m_aud;

    void Start ()
    {
        m_filePath = Application.dataPath + "/Resources/" + "mov.mp4";
        m_aud = GetComponent <AudioSource> ();
    }

    void OnGUI ()
    {
        if (GUILayout.Button ("播放")) {
            if (File.Exists (m_filePath)) {
                StartCoroutine (Playing ());
            } else {
                StartCoroutine (DownLoading ());
            }
        }
    }
    //播放
    IEnumerator Playing ()
    {
        while (movie == null) {
            movie = Resources.Load ("mov") as MovieTexture;
            yield return null;
        }
        GetComponent <MeshRenderer> ().material.mainTexture = movie;
        m_aud.clip = movie.audioClip;
        m_aud.loop = true;
        movie.loop = true;
        m_aud.Play ();
        movie.Play ();
    }

    //下载
    IEnumerator DownLoading ()
    {
        WWW w = new WWW (url);
        while (w.isDone == false) {
            print (w.progress);
            yield return null;
        }

        try {
            //视频写入
            File.WriteAllBytes (m_filePath, w.bytes);
        } catch (System.Exception ex) {
            print (ex);
        }
        //刷新Asset
        AssetDatabase.Refresh ();
        StartCoroutine (Playing ());
    }

}

3.运行调试

由于需要下载,下图等待即可看到效果

运行结果

如果有疑问,请留言, 欢迎提供更好的办法.

如果觉得本文对你有所帮助, 欢迎添加喜欢.
如需转载,请标明出处.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容