下图是最终效果
下图是用来播放视频的UI 上面需要挂的俩个组件
下图是创建VideoRenderTexture的步骤
上代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;
public class VideoView : MonoBehaviour
{
public Button closeBtn;
public VideoPlayer video;
public Toggle tog;//暂停与播放
public MySlider slider;//作为滑动进度的
public Text timeText;//显示文字的
public Image Fill;//作为显示进度的
// Start is called before the first frame update
void Awake()
{
video.source = VideoSource.Url;
tog.onValueChanged.AddListener((pag) =>
{
tog.transform.GetChild(0).gameObject.SetActive(!pag);
if (pag)
{
video.Pause();
}
else
{
video.Prepare();
video.Play();
UnityHttpHelper.Ins.StartCoroutine(OnUpdate());
}
});
slider.onValueChanged.AddListener((o) => { video.frame = long.Parse((o * video.frameCount).ToString("0.")); Fill.fillAmount = o; SetTime(); });
slider.beiginDrag = beiginDrag;
slider.endDrag = endDrag;
closeBtn.onClick.AddListener(() => { gameObject.SetActive(false); });
}
bool taggle = true;
private void endDrag()
{
taggle = true;
}
private void beiginDrag()
{
taggle = false;
}
public void SetVideo(string url)
{
video.Prepare();
video.url = url;
gameObject.SetActive(true);
OnPlayerFalse(true);
UnityHttpHelper.Ins.StartCoroutine(OnUpdate());
}
int hour = 0;//小时
int minte = 0;//分钟
int second = 0;//秒
int hourAll = 0;
int minteAll = 0;
int secondAll = 0;
IEnumerator OnUpdate()
{
while (true)
{
yield return new WaitForSeconds(0.05f);
//await Task.Delay(5);
if (video.isPlaying == true)
{
break;
}
}
while (true)
{
yield return new WaitForSeconds(0.05f);
//await Task.Delay(5);
if (video.url == null) yield break;
//slider.value = (float.Parse(video.frame.ToString()) / float.Parse(video.frameCount.ToString()));
if (taggle == true)
Fill.fillAmount = (float.Parse(video.frame.ToString()) / float.Parse(video.frameCount.ToString()));
SetTime();
if (video.isPlaying == false)
{
Debug.Log("111111111111");
OnPlayerFalse(video.isPlaying);
yield break;
}
}
}
void SetTime()
{
//hour = (int)(video.time / 3600);
//minte = (int)((video.time - hour * 3600) / 60);
//second = (int)(video.time - hour * 3600 - minte * 60);
minte = (int)(video.time / 60);
second = (int)(Math.Round(video.time) - (ulong)(minte * 60));
//minte = (int)(video.frame / 60);
//second = (int)(video.frame - (minte * 60));
minteAll = (int)(video.length / 60);
secondAll = (int)(video.length - minteAll * 60);
timeText.text = $"{minte.ToString("D2")}:{second.ToString("D2")} / {minteAll.ToString("D2")}:{secondAll:D2}";
//timeText.text = $"{hour.ToString("D2")}:{minte.ToString("D2")}:{second.ToString("D2")} / {hourAll.ToString("D2")}:{minteAll.ToString("D2")}:{secondAll:D2}";
}
//设置暂停与播放状态
void OnPlayerFalse(bool isPlay)
{
tog.isOn = !isPlay;
}
}