using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; using UnityEngine.UI; using System; [RequireComponent(typeof(VideoPlayer))] public class VideoPanel : MonoBehaviour { public VideoPlayer videoPlayer; public Toggle beginToggle; public Slider videoSlider; public Text videoLength;//显示视频总时间 public Text playLength;//显示视频已播时间 public bool skip; private float totalVideoLength; private bool isPlaying; // Use this for initialization void Start() { videoPlayer.sendFrameReadyEvents = true;//打开开关们才能接受frameReady事件 videoPlayer.loopPointReached += OnFinish; videoPlayer.prepareCompleted += OnPrepared; videoPlayer.frameReady += OnFrameReady; } /// /// 更新播放中进度条的值和显示时间 /// /// /// private void OnFrameReady(VideoPlayer source, long frameIdx) { //由于存在跳帧的情况,在播完的情况下不会再给进度条和显示时间赋值,直接在完成的回调里赋值 if (isPlaying) { float time = (float)videoPlayer.time; playLength.text = FloatToTime(time); if (!skip) { videoSlider.value = time; } } } void OnDestroy() { videoPlayer.loopPointReached -= OnFinish; videoPlayer.prepareCompleted -= OnPrepared; videoPlayer.frameReady -= OnFrameReady; } // Update is called once per frame void Update() { /* if (videoPlayer.isPlaying) { float time = (float)videoPlayer.time; playLength.text = FloatToTime(time); if (!skip) { videoSlider.value = (float)videoPlayer.time; } } */ if (skip) { float time = (float)videoPlayer.time; playLength.text = FloatToTime(time); } } /// /// 播放视频文件 /// /// public void PlayVideo(string videoFile) { gameObject.SetActive(true); beginToggle.isOn = true; videoPlayer.url = videoFile; videoPlayer.Play(); isPlaying = true; } /// /// 继续播放 /// public void Play() { videoPlayer.Play(); isPlaying = true; } /// /// 暂停播放 /// public void Pause() { videoPlayer.Pause(); } /// /// 停止播放 /// public void StopVideo() { videoPlayer.Stop(); gameObject.SetActive(false); } private void OnPrepared(VideoPlayer source) { totalVideoLength = videoPlayer.frameCount / videoPlayer.frameRate; videoSlider.maxValue = totalVideoLength; videoLength.text = FloatToTime(totalVideoLength); } private void OnFinish(VideoPlayer source) { beginToggle.isOn = false; playLength.text = FloatToTime(totalVideoLength); isPlaying = false; } private string FloatToTime(float time) { //int hour = (int)time / 3600; //int min = (int)(time - hour * 3600) / 60; //int sec = (int)(time - hour * 3600) % 60; //string text = string.Format("{0:D2}:{1:D2}:{2:D2}", hour, min, sec); var timespan = TimeSpan.FromSeconds(time); var text = string.Format("{0:D2}:{1:D2}:{2:D2}", timespan.Hours, timespan.Minutes, timespan.Seconds); return text; } }