上海杨浦大连路地铁站单机版电子沙盘
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

133 lines
3.7 KiB

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;
}
/// <summary>
/// 更新播放中进度条的值和显示时间
/// </summary>
/// <param name="source"></param>
/// <param name="frameIdx"></param>
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);
}
}
/// <summary>
/// 播放视频文件
/// </summary>
/// <param name="videoFile"></param>
public void PlayVideo(string videoFile)
{
gameObject.SetActive(true);
beginToggle.isOn = true;
videoPlayer.url = videoFile;
videoPlayer.Play();
isPlaying = true;
}
/// <summary>
/// 继续播放
/// </summary>
public void Play()
{
videoPlayer.Play();
isPlaying = true;
}
/// <summary>
/// 暂停播放
/// </summary>
public void Pause()
{
videoPlayer.Pause();
}
/// <summary>
/// 停止播放
/// </summary>
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;
}
}