using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using BITKit; using UnityEngine.InputSystem; using Cysharp.Threading.Tasks; using System.Threading.Tasks; namespace BITKit.Media { public class VideoPlayer : MediaPlayer { const string timeFormat = "HH:mm:ss"; [Header(Constant.Header.Settings)] public InputAction playOrPauseAction; public bool log; [Header(Constant.Header.Debug)] public string currentTimeAsString; void Enable() { playOrPauseAction.Enable(); } void Disable() { playOrPauseAction.Disable(); } protected override void OnStart() { playOrPauseAction.performed += OnPlayOrPause; Prepare(); } public override void Play() { if (isPlaying is false) { if (log) { BIT4Log.Log($"开始播放视频:{player.clip.name}"); } DateTime totalDateTime = new(); player.Play(); isPlaying = true; onStartPlay.Invoke(); totalDateTime = totalDateTime.AddSeconds(player.length); onSetTotalTime.Invoke((float)player.length); onSetTotalTimeAsString.Invoke(totalDateTime.ToString(timeFormat)); } else { PlayOrPause(); } } public override void Stop() { if (isPlaying) { player.Stop(); isPlaying = false; onStopPlay.Invoke(); } } public void Pause() { if (isPlaying) { if (player.isPaused is false) { onPause.Invoke(); player.Pause(); } } } public override void PlayOrPause() { if (isPlaying) { if (player.isPaused) { onPlay.Invoke(); player.Play(); } else { Pause(); } } else { Play(); } } public override void UpdateProgess() { if (player.isPlaying && player.isPaused is false) { DateTime playDateTime = new(); var doubleTime = player.time / player.length; currentTime = (float)doubleTime; playDateTime = playDateTime.AddSeconds(player.time); onTime.Invoke(currentTime); currentTimeAsString = playDateTime.ToString(timeFormat); onTimeAsString.Invoke(currentTimeAsString); } } public override void SetNormalizeTime(float time) { player.time = Mathf.Lerp(0, (float)player.length, time); } public override void Set(T obj) { switch (obj) { case float time: SetNormalizeTime(time); break; } } public async void Prepare() { player.Prepare(); Stop(); SetNormalizeTime(0); Play(); await Task.Delay(128, gameObject.GetCancellationTokenOnDestroy()); Stop(); SetNormalizeTime(0); } void OnPlayOrPause(InputAction.CallbackContext context) { Debug.Log(context); PlayOrPause(); } } }