且行且珍惜
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.運行調試
由于需要下載,下圖等待即可看到效果
運行結果
如果有疑問,請留言, 歡迎提供更好的辦法.
如果覺得本文對你有所幫助, 歡迎添加喜歡.
如需轉載,請標明出處.