网上大家也写了很多Unity3D中播放视频的教程,关于播放外部视频的还是比较少,所以写这篇文章,不足之处,还望读者指正。
在Unity3D中,我们一般使用播放视频的方法:将*.mov,*.mp4等格式拖拽到Asset中目录,Unity3D会转换为MovieTexture,音频AudioClip在子节点可找到。但,如果我们想动态加载外部视频,该怎么做呢?以下附上实现脚本,可自行修改。
- using UnityEngine;
- using System.Collections;
- using System.IO;
- //[RequireComponent(typeof(AudioSource))]
- public class MoviePlayer : MonoBehaviour
- {
- private MovieTexturemovieTexture;//
- private string movieDir = "/Data/Movie";//根目录下
- private float movietime;
- privatestatic MoviePlayer instance;
- public static MoviePlayer Instance
- {
- get
- {
- return instance;
- }
- }
- void Start()
- {
- StartCoroutine(DownloadMovie());
- Play();
- instance = this;
- }
- public void Play()
- {
- audio.Play();
- movieTexture.Play();
- Debug.Log("Play");
- }
- public void Pause()
- {
- audio.Pause();
- movieTexture.Pause();
- Debug.Log("Pause");
- }
- public void Stop()
- {
- audio.Stop();
- movieTexture.Stop();
- Debug.Log("Stop");
- }
- public bool IsPlaying()
- {
- return audio.isPlaying;
- }
- public float GetMovieTime()
- {
- return audio.time;
- }
- IEnumerator DownloadMovie()
- {//WWW www = new WWW("file:///D://Project//Movie/Data/Movie//movie.ogv");
- string[] files = Directory.GetFiles(Directory.GetCurrentDirectory() +movieDir);//PC版,其他版本只需要修改视频文件读取方式
- WWW www = new WWW("file:///" + files[0]);
- movieTexture = (MovieTexture)www.movie;
- while(!movieTexture.isReadyToPlay)
- yield return www;
- renderer.material.mainTexture = movieTexture;//视频纹理
- audio.clip = movieTexture.audioClip;//音频
- Play();
- }
- }