赞
踩
在之前的公司,项目里经常会有使用Unity开发播放视频的功能。Unity播放视频有好几种方式,如Videoplayer,movieTexture,AVPro等。我比较喜欢用VideoPlayer这个组件,使用非常方便,几乎能满足所有的开发需求,开发起来也十分方便。这篇博客简单介绍了一下VideoPlayer组件的基本使用步骤,下面是具体步骤:
1.建立一个空场景,在场景中创建如下组件,如图所示:
2.在Assets文件夹下建立StreamingAssets文件夹,将测试视频放在文件夹下,如下图所示:
3.创建PlayVideo.cs脚本,脚本代码如下所示:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; using UnityEngine.UI; namespace MoviePlay { public class PlayVideo : MonoBehaviour { #region 参数 //定义参数获取video组件和RawImage组件 VideoPlayer videoPlayer; public RawImage rawImage; public string[] movieUrl; bool isPlay = false; //声音播放组件 private AudioSource thisAudioSource; //是否静音 bool isMute = false; #endregion // Use this for initialization void Start() { BeginString(); } // Update is called once per frame void Update() { PlayMovie(); } #region 私有方法 /// <summary> /// 初始化数据 /// </summary> void BeginString() { videoPlayer = GameObject.Find("moviePlayManager").GetComponent<VideoPlayer>(); thisAudioSource = GameObject.Find("moviePlayManager").GetComponent<AudioSource>(); movieUrl[0] = Application.streamingAssetsPath + "/Zero.mp4"; isPlay = false; } /// <summary> /// 播放视频函数 /// </summary> void PlayMovie() { //如果videoPlayer没有对应的视频texture,则返回 if (videoPlayer.texture == null) { return; } //把VideoPlay的视频渲染到UGUI的RawImage上 rawImage.texture = videoPlayer.texture; if (isPlay) { if (videoPlayer.frame == (long)videoPlayer.frameCount) { Debug.Log("视频播放完毕动作!"); } } } /// <summary> /// 播放视频0逻辑 /// </summary> public void ToPlayThis0() { videoPlayer.url = movieUrl[0]; StartCoroutine(ToPlay0()); } /// <summary> /// 播放视频0的协程 /// </summary> /// <returns></returns> IEnumerator ToPlay0() { yield return new WaitForSeconds(0.1f); BeginPlay(); } /// <summary> /// 开始播放视频 /// </summary> void BeginPlay() { if (!isPlay) { videoPlayer.Play(); isPlay = true; } } /// <summary> /// 停止播放视频 /// </summary> public void StopPlay() { if (isPlay) { videoPlayer.Stop(); isPlay = false; } } /// <summary> /// 暂停播放视频逻辑 /// </summary> public void PauseThis() { if (isPlay) { videoPlayer.Pause(); isPlay = false; } else { videoPlayer.Play(); isPlay = true; } } /// <summary> /// 增加音量逻辑 /// </summary> public void AddVolume() { thisAudioSource.volume += 0.1f; } /// <summary> /// 减小音量逻辑 /// </summary> public void DecreaseVolume() { thisAudioSource.volume -= 0.1f; } /// <summary> /// 静音功能 /// </summary> public void MuteVolume() { if (!isMute) { thisAudioSource.mute = true; isMute = true; } else { thisAudioSource.mute = false; isMute = false; } } #endregion } }
4.将此脚本挂载到moviePlayManager物体上,同时在此物体上添加VideoPlayer和AudioSource组件,将RawImage拖拽到此物体挂载的脚本上,如下图所示:
5.将PlayVideo.cs脚本的方法添加到对应的按钮中,基本完成视频功能的开发,如下图所示:
实现效果如下图所示,只能放个无声的gif图了(珍珠港片段),需要测试声音功能的话自己去搭建场景吧…
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。