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.運行調試

由于需要下載,下圖等待即可看到效果

運行結果

如果有疑問,請留言, 歡迎提供更好的辦法.

如果覺得本文對你有所幫助, 歡迎添加喜歡.
如需轉載,請標明出處.
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容