Unity学习笔记之VideoPlayer实现视频播放器效果
需求:实现一个视频播放器所拥有的的所有功能。
1:视频进度条实时更新
private void VideoSliderUpdate()//视频进度条更新
{
slider_ShiPin.value = (float)Math.Round(videoPlayer.clockTime, 2);
txt_SliderTime.text = (float)Math.Round(videoPlayer.clockTime, 2) + "/" + videoMaxLength;
}
下面附一下我写这个播放器的全部代码:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;
public enum VideoPlayModel
{
FeiQuanPing,
QuanPing,
}
public class VideoPlayerOnly : MonoBehaviour
{
public VideoPlayer videoPlayer;
VideoPlayModel videoPlayModel;
[Header("****************视频****************")]
public Text txt_ShiPinName;
public Slider slider_ShiPin;
public Text txt_SliderTime;
public Slider slider_Audio;
WaitForSeconds wfs = new WaitForSeconds(0.02f);
public Button btn_PlayOrPauseBig;
public Button btn_PlayOrPauseSmall;
public Sprite[] sprites;
private void AudioChange()//音量大小调节
{
AudioSource audioSource = videoPlayer.GetTargetAudioSource(0);
audioSource.volume = slider_Audio.value;
}
private void VideoChange()//视频进度拖动预留(后面再增加)
{
if (!isCanUpdate)
videoPlayer.time = slider_ShiPin.value;
}
private void UpdateVideoPlayTime()//更新视频进度条
{
slider_ShiPin.maxValue = (int)videoPlayer.length;
slider_ShiPin.value = (int)videoPlayer.time;
txt_SliderTime.text = TimeZhuanHuan((int)videoPlayer.time) + "/" + TimeZhuanHuan((int)videoPlayer.length);
}
#region 时间转换(秒转为时分秒)
string str_Hour, str_Minute, str_Second;
public string TimeZhuanHuan(int s)
{
int hour, minute, second;
second = s % 60;//17
minute = ((s / 60)) % 60;//7
hour = (s / 60 / 60) % 60;
if (hour < 10) str_Hour = "0" + hour;
else str_Hour = hour.ToString();
if (minute < 10) str_Minute = "0" + minute;
else str_Minute = minute.ToString();
if (second < 10) str_Second = "0" + second;
else str_Second = second.ToString();
return str_Hour + ":" + str_Minute + ":" + str_Second;
}
#endregion
bool isPlaying;
public void PlayAndPause()
{
//isVideoStop = true;
if (isPlaying)
ClickVideoPause();
else
ClickVideoPlay();
isPlaying = !isPlaying;
}
private void ClickVideoPlay()
{
videoPlayer.Play();
btn_PlayOrPauseBig.GetComponent<Image>().sprite = sprites[0];
btn_PlayOrPauseSmall.GetComponent<Image>().sprite = sprites[1];
}
private void ClickVideoPause()
{
videoPlayer.Pause();
btn_PlayOrPauseBig.GetComponent<Image>().sprite = sprites[2];
btn_PlayOrPauseSmall.GetComponent<Image>().sprite = sprites[3];
}
public void StopVideo()
{
videoPlayer.Stop();
isPlaying = false;
ClickVideoPause();
}
private void InitShiPin()
{
slider_Audio.onValueChanged.AddListener(delegate { AudioChange(); });
slider_Audio.maxValue = 100;
slider_ShiPin.maxValue = (float)videoPlayer.length;
slider_ShiPin.value = 0;
btn_PlayOrPauseBig.onClick.AddListener(delegate { PlayAndPause(); });
btn_PlayOrPauseSmall.onClick.AddListener(delegate { PlayAndPause(); });
}
public void ClickShiPin(int index)
{
Scene scene = SceneManager.GetActiveScene();
string s = "";
if (scene.name == "Init")//介绍里面的视频
{
txt_ShiPinName.text = AnalysisJSON.GetJieShaoVideoName(index);
s = Application.streamingAssetsPath + "/JiaoHuSceneVideo/" + AnalysisJSON.GetJieShaoVideoPath(index);
}
else if (scene.name == "JiaoHuScene0")//交互场景的视频
{
txt_ShiPinName.text = AnalysisJSON.GetJiaoHuSceneVideoName(index);
s = Application.streamingAssetsPath + "/JiaoHuSceneVideo/" + AnalysisJSON.GetJiaoHuSceneVideoPath(index);
}
videoPlayer.url = s;
slider_ShiPin.value = 0;
videoPlayer.Play();
PlayAndPause();
}
private void Awake()
{
InitShiPin();
slider_ShiPin.onValueChanged.AddListener(delegate { VideoChange(); });
}
private void Start()
{
CanvasInit();
}
public bool isCanUpdate;
public void QuanPingVideo()
{
isCanUpdate = false;
AudioSource audioSource = videoPlayer.GetTargetAudioSource(0);
audioSource.volume = 0;
PlayAndPause();
}
private void Update()
{
if (isCanUpdate)
{
UpdateVideoPlayTime();
ImageUpdate();
}
if (GetUI() != null)
{
if (GetUI().name == "Fill" && Input.GetMouseButtonDown(0))
{
isCanUpdate = false;
}
else if (Input.GetMouseButtonUp(0))
{
isCanUpdate = true;
}
}
}
#region 全屏
[Header("****************全屏****************")]
public RectTransform quanPin_Rect;//全屏需要更改的RectTransform
public Transform quanPin_Parent;//非全屏状态下的父物体
public GameObject bu_Up;//最上方的介绍、图片、视频按钮父物体
bool isQuanPing;//是否全屏
public void IsQuanPin()
{
isQuanPing = !isQuanPing;
bu_Up.SetActive(!isQuanPing);
if (isQuanPing)
{
quanPin_Rect.transform.parent = transform;
quanPin_Rect.anchoredPosition = new Vector2(1018, -510);
quanPin_Rect.sizeDelta = new Vector2(2036, 1018);
}
else
{
quanPin_Rect.transform.parent = quanPin_Parent;
quanPin_Rect.anchoredPosition = new Vector2(0, 0);
quanPin_Rect.sizeDelta = new Vector2(800, 450);
}
StartCoroutine(RefreshQuanPing());
}
IEnumerator RefreshQuanPing()
{
RectTransform rect = quanPin_Rect.transform.parent.GetComponent<RectTransform>();
yield return new WaitForEndOfFrame();
LayoutRebuilder.MarkLayoutForRebuild(rect);
yield return new WaitForEndOfFrame();
LayoutRebuilder.MarkLayoutForRebuild(rect);
yield return new WaitForEndOfFrame();
LayoutRebuilder.MarkLayoutForRebuild(rect);
yield return new WaitForEndOfFrame();
LayoutRebuilder.MarkLayoutForRebuild(rect);
}
#endregion
#region 视频播放按钮透明度改变
private static GraphicRaycaster canvas;
public void CanvasInit()//必须获取到Canvas上的GraphicRaycaster组件才可以开始监听
{
canvas = OverallSituation.instance.mainCanvas.GetComponent<GraphicRaycaster>();
}
/// <summary>
/// 获取鼠标停留处UI
/// </summary>
public static GameObject GetUI()
{
if (canvas == null) return null;
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = Input.mousePosition;
GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
gr.Raycast(pointerEventData, results);
if (results.Count != 0)
{
return results[0].gameObject;
}
return null;
}
Color c = Color.white;
float maxTime = 1;
float time = 0;
bool isStop;
IEnumerator ColorAChange(bool isEnter)
{
if (isEnter)
{
time = 0;
while (time <= maxTime)
{
yield return new WaitForSeconds(Time.deltaTime * 10);
c.a -= Time.deltaTime;
btn_PlayOrPauseBig.GetComponent<Image>().color = c;
time += Time.deltaTime;
}
isStop = true;
}
else
{
c.a = 1;
btn_PlayOrPauseBig.GetComponent<Image>().color = Color.white;
isStop = true;
}
}
public void ImageUpdate()//时刻更新
{
if (GetUI() != null)
{
if (GetUI().name == "btn_PlayOrPauseBig")
{
if (isStop)
{
StopAllCoroutines();
isStop = false;
}
StartCoroutine(ColorAChange(false));
}
else
{
if (isStop)
{
StopAllCoroutines();
isStop = false;
}
StartCoroutine(ColorAChange(true));
}
}
else
{
if (isStop)
{
StopAllCoroutines();
isStop = false;
}
StartCoroutine(ColorAChange(true));
}
}
#endregion
}
稍微修改了一下时间转换
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)