美文网首页Unity教程合集Unity技术分享征服Unity3d
Unity内播放网络或者本地视频(非工程文件内)

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

作者: Jens丶 | 来源:发表于2017-04-13 18:13 被阅读0次
    且行且珍惜
    
    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.运行调试

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

    运行结果

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

    如果觉得本文对你有所帮助, 欢迎添加喜欢.
    如需转载,请标明出处.
    

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/jyabattx.html