一. 最简单的方法 新建一个canvas,把 mp4视频(其它格式的应该也可以,没有试过)拖到 Canvas 下,什么都不用改,可以直接播放视频,此时全屏播放。 如下图:
效果如下图:
二. 通过RawImage播放视频
无法直接拖video到raw image的texture上,另外在RawImage上通过add component的方式添加video player也不行,需要一个叫Render Texture的控件关联。
参考:(78条消息) Unity UGUI Raw Image中文详解-Chinar_ChinarCSDN的博客-CSDN博客_rawimage
1. 新建一个空的New Render Texture(应该是关联video和raw image用的)
2.raw image控件上通过add component的方式添加video player
3. 把要播放的视频拖到 video player上的video clip中,把第1步中的New Render Texture分别拖到video player上的target texture中(如下图)
和raw image控件上的raw image的texture中,如下图。
大公告成,raw image控件播放video的好处是可以控制大小,但后来一想canvas调了大小也可以的吧,只是没测而已,好像没有优势。
3.使用url方式播放video,参考链接unity 播放视频videoplayer - 灰信网(软件开发博客聚合) (freesion.com)代码如下
using System.Collections;
using UnityEngine;
using UnityEngine.Video;
public class NewBehaviourScript : MonoBehaviour
{
//public RawImage image;
public VideoClip videoToPlay;
private VideoPlayer videoPlayer;
private VideoSource videoSource;
private AudioSource audioSource;
// Use this for initialization
void Start()
{
Application.runInBackground = true;
StartCoroutine(playVideo());
}
IEnumerator playVideo()
{
//Add VideoPlayer to the GameObject
videoPlayer = gameObject.AddComponent<VideoPlayer>();
//Add AudioSource
audioSource = gameObject.AddComponent<AudioSource>();
//Disable Play on Awake for both Video and Audio
videoPlayer.playOnAwake = false;
audioSource.playOnAwake = false;
audioSource.Pause();
//We want to play from video clip not from url
videoPlayer.source = VideoSource.VideoClip;
// Vide clip from Url
//videoPlayer.source = VideoSource.Url;
//videoPlayer.url = "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
//Set Audio Output to AudioSource
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
//Assign the Audio from Video to AudioSource to be played
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.clip = videoToPlay;
videoPlayer.Prepare();
//Wait until video is prepared
WaitForSeconds waitTime = new WaitForSeconds(1);
while (!videoPlayer.isPrepared)
{
Debug.Log("Preparing Video");
//Prepare/Wait for 5 sceonds only
yield return waitTime;
//Break out of the while loop after 5 seconds wait
break;
}
Debug.Log("Done Preparing Video");
//Assign the Texture from Video to RawImage to be displayed
//image.texture = videoPlayer.texture;
//Play Video
videoPlayer.Play();
/*videoPlayer.controlledAudioTrackCount = 1; // <-- We have added this line. It tells video player that you will have one audio track playing in Unity AudioSource.
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);*/
//Play Sound
audioSource.Play();
Debug.Log("Playing Video");
while (videoPlayer.isPlaying)
{
Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
yield return null;
}
Debug.Log("Done Playing Video");
}
}