hch
2 小时以前 8d2b635a2add75c74c2b4aaab7bc970825f95254
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
using System;
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.UI;
 
/// <summary>
/// UI视频播放器组件 - 支持WebM格式透明视频播放
/// </summary>
public class UIVideoPlayer : MonoBehaviour
{
    [Header("组件引用")]
    public VideoPlayer videoPlayer;
    public RawImage videoImage;
 
    [Header("调试信息")]
    public const string directory = "Video";
    public string videoName;
    public bool isLoop = false;
    
    [Header("资源管理")]
    [Tooltip("播放完成后是否自动卸载资源(仅当非循环播放时有效)")]
    public bool autoUnloadOnFinish = true;
    
    [Header("回调事件")]
    public Action onComplete;
    public Action onPrepared;
 
    private RenderTexture _renderTexture;
    private VideoClip _loadedClip;
    private bool _isPrepared;
    private bool _isLoading;
    private Action<bool> _onPrepareCallback;
 
    #region Public API
 
    /// <summary>
    /// 加载并播放视频(通过资源系统加载 VideoClip)
    /// </summary>
    /// <param name="_videoName">视频文件名(不含扩展名)</param>
    /// <param name="_loop">是否循环播放</param>
    /// <param name="_onComplete">播放完成回调(仅在非循环播放时调用)</param>
    public async void LoadAndPlayVideo(string _videoName, bool _loop = false, Action _onComplete = null)
    {
        if (!ValidateComponents()) return;
        if (_isLoading)
        {
            Debug.LogWarning($"UIVideoPlayer: Already loading video. Please wait.");
            return;
        }
 
        videoName = _videoName;
        isLoop = _loop;
        onComplete = _onComplete;
        _isPrepared = false;
        _isLoading = true;
 
        // 清理旧资源
        ReleaseRenderTexture();
        
        // 隐藏或设置空状态颜色
        SetEmptyState();
 
        // 通过 ResManager 加载 VideoClip 资源(支持 AB 打包)
        _loadedClip = await ResManager.Instance.LoadAssetAsync<VideoClip>(directory, videoName, false);
        
        // 检查是否在加载过程中被取消
        if (!_isLoading)
        {
            _loadedClip = null;
            return;
        }
        
        _isLoading = false;
        
        if (_loadedClip == null)
        {
            Debug.LogError($"UIVideoPlayer: Failed to load VideoClip: {directory}/{videoName}");
            _isPrepared = false;
            return;
        }
 
        // 创建并绑定 RenderTexture(按视频实际尺寸)
        _renderTexture = new RenderTexture((int)_loadedClip.width, (int)_loadedClip.height, 0);
        videoPlayer.targetTexture = _renderTexture;
        videoImage.texture = _renderTexture;
        videoImage.SetNativeSize();
 
        
        // 显示视频
        SetActiveState();
 
        videoPlayer.source = VideoSource.VideoClip;
        videoPlayer.clip = _loadedClip;
        videoPlayer.isLooping = isLoop;
        videoPlayer.prepareCompleted += OnVideoPrepared;
        
        // 非循环播放时注册完成事件
        if (!isLoop)
        {
            videoPlayer.loopPointReached += OnVideoFinished;
        }
        
        videoPlayer.Prepare();
    }
 
    /// <summary>
    /// 加载并播放指定视频
    /// </summary>
    public void LoadAndPlay(string videoName, bool loop = false, Action onCompleteCallback = null)
    {
        LoadAndPlayVideo(videoName, loop, onCompleteCallback);
    }
 
    [ContextMenu("播放")]
    public void Play()
    {
        if (!ValidateComponents()) return;
        if (_isPrepared && !videoPlayer.isPlaying)
        {
            videoPlayer.Play();
        }
    }
    
    [ContextMenu("暂停")]
    public void Pause()
    {
        if (!ValidateComponents()) return;
        if (videoPlayer.isPlaying)
        {
            videoPlayer.Pause();
        }
    }
    
    [ContextMenu("恢复")]
    public void Resume()
    {
        if (!ValidateComponents()) return;
        if (_isPrepared && !videoPlayer.isPlaying)
        {
            videoPlayer.Play();
        }
    }
 
    /// <summary>
    /// 预加载视频(不自动播放)
    /// </summary>
    /// <param name="_videoName">视频文件名(不含扩展名)</param>
    /// <param name="onPreparedOK">预加载完成回调,参数为是否成功</param>
    public async void Prepare(string _videoName, Action<bool> onPreparedOK)
    {
        if (!ValidateComponents())
        {
            onPreparedOK?.Invoke(false);
            return;
        }
        
        if (_isLoading)
        {
            Debug.LogWarning($"UIVideoPlayer: Already loading video. Please wait.");
            onPreparedOK?.Invoke(false);
            return;
        }
 
        videoName = _videoName;
        _onPrepareCallback = onPreparedOK;
        _isPrepared = false;
        _isLoading = true;
 
        // 清理旧资源
        ReleaseRenderTexture();
        SetEmptyState();
 
        // 通过 ResManager 加载 VideoClip 资源(支持 AB 打包)
        _loadedClip = await ResManager.Instance.LoadAssetAsync<VideoClip>(directory, videoName, false);
        
        // 检查是否在加载过程中被取消
        if (!_isLoading)
        {
            _loadedClip = null;
            return;
        }
        
        _isLoading = false;
        
        if (_loadedClip == null)
        {
            Debug.LogError($"UIVideoPlayer: Failed to load VideoClip: {directory}/{videoName}");
            _isPrepared = false;
            _onPrepareCallback?.Invoke(false);
            _onPrepareCallback = null;
            return;
        }
 
        // 创建并绑定 RenderTexture(按视频实际尺寸)
        _renderTexture = new RenderTexture((int)_loadedClip.width, (int)_loadedClip.height, 0);
        videoPlayer.targetTexture = _renderTexture;
        videoImage.texture = _renderTexture;
        videoImage.SetNativeSize();
        
        SetActiveState();
 
        videoPlayer.source = VideoSource.VideoClip;
        videoPlayer.clip = _loadedClip;
        videoPlayer.prepareCompleted += OnVideoPreparedForPreload;
        
        videoPlayer.Prepare();
    }
    
    /// <summary>
    /// 通过 URL 加载并播放视频
    /// </summary>
    /// <param name="url">视频 URL 地址</param>
    /// <param name="_loop">是否循环播放</param>
    /// <param name="_onComplete">播放完成回调(仅在非循环播放时调用)</param>
    public void LoadAndPlayFromURL(string url, bool _loop = false, Action _onComplete = null)
    {
        if (!ValidateComponents()) return;
        if (_isLoading)
        {
            Debug.LogWarning($"UIVideoPlayer: Already loading video. Please wait.");
            return;
        }
 
        videoName = url;
        isLoop = _loop;
        onComplete = _onComplete;
        _isPrepared = false;
        _isLoading = true;
 
        // 清理旧资源
        ReleaseRenderTexture();
        SetEmptyState();
 
        // 根据 URL 视频创建默认尺寸的 RenderTexture(准备完成后会调整)
        _renderTexture = new RenderTexture(1920, 1080, 0);
        videoPlayer.targetTexture = _renderTexture;
        videoImage.texture = _renderTexture;
        
        SetActiveState();
 
        videoPlayer.source = VideoSource.Url;
        videoPlayer.url = url;
        videoPlayer.isLooping = isLoop;
        videoPlayer.prepareCompleted += OnVideoPreparedForURL;
        
        // 非循环播放时注册完成事件
        if (!isLoop)
        {
            videoPlayer.loopPointReached += OnVideoFinished;
        }
        
        videoPlayer.Prepare();
    }
    
    [ContextMenu("停止")]
    public void Stop()
    {
        if (!ValidateComponents()) return;
        videoPlayer.Stop();
    }
    
    [ContextMenu("重新播放")]
    public void Restart()
    {
        if (!ValidateComponents()) return;
        if (_isPrepared)
        {
            videoPlayer.Stop();
            videoPlayer.Play();
        }
    }
 
    /// <summary>
    /// 卸载视频资源
    /// </summary>
    public void Unload()
    {
        if (videoPlayer == null) return;
 
        // 取消所有事件订阅
        videoPlayer.prepareCompleted -= OnVideoPrepared;
        videoPlayer.prepareCompleted -= OnVideoPreparedForPreload;
        videoPlayer.prepareCompleted -= OnVideoPreparedForURL;
        videoPlayer.loopPointReached -= OnVideoFinished;
        
        videoPlayer.Stop();
        videoPlayer.clip = null;
        videoPlayer.url = null;
        videoPlayer.targetTexture = null;
        
        if (videoImage != null)
        {
            videoImage.texture = null;
        }
 
        _loadedClip = null;
        ReleaseRenderTexture();
        
        // 恢复空状态
        SetEmptyState();
 
        _isPrepared = false;
        _isLoading = false;
        onComplete = null;
        onPrepared = null;
    }
 
    #endregion
 
    #region Properties
 
    /// <summary>
    /// 视频是否已准备好
    /// </summary>
    public bool IsPrepared => _isPrepared;
 
    /// <summary>
    /// 视频是否正在播放
    /// </summary>
    public bool IsPlaying => videoPlayer != null && videoPlayer.isPlaying;
 
    /// <summary>
    /// 视频是否正在加载
    /// </summary>
    public bool IsLoading => _isLoading;
 
    /// <summary>
    /// 当前播放时间(秒)
    /// </summary>
    public double CurrentTime => videoPlayer != null ? videoPlayer.time : 0;
 
    /// <summary>
    /// 视频总时长(秒)
    /// </summary>
    public double Duration => _loadedClip != null ? _loadedClip.length : 0;
 
    #endregion
 
    #region Private Methods
 
    [ContextMenu("重新加载")]
    private void Reload()
    {
        LoadAndPlayVideo(videoName, isLoop);
    }
 
    private void OnVideoPrepared(VideoPlayer vp)
    {
        vp.prepareCompleted -= OnVideoPrepared;
        _isPrepared = true;
        _isLoading = false;
        onPrepared?.Invoke();
        vp.Play();
    }
    
    private void OnVideoPreparedForPreload(VideoPlayer vp)
    {
        vp.prepareCompleted -= OnVideoPreparedForPreload;
        _isPrepared = true;
        _isLoading = false;
        _onPrepareCallback?.Invoke(true);
        _onPrepareCallback = null;
        // 预加载完成后不自动播放
    }
    
    private void OnVideoPreparedForURL(VideoPlayer vp)
    {
        vp.prepareCompleted -= OnVideoPreparedForURL;
        _isPrepared = true;
        _isLoading = false;
        
        // 调整 RenderTexture 尺寸为实际视频尺寸
        if (_renderTexture != null && vp.texture != null)
        {
            var newRT = new RenderTexture((int)vp.width, (int)vp.height, 0);
            ReleaseRenderTexture();
            _renderTexture = newRT;
            vp.targetTexture = _renderTexture;
            videoImage.texture = _renderTexture;
            videoImage.SetNativeSize();
        }
        
        onPrepared?.Invoke();
        vp.Play();
    }
 
    private void OnVideoFinished(VideoPlayer vp)
    {
        onComplete?.Invoke();
        
        // 根据设置自动清理资源
        if (autoUnloadOnFinish)
        {
            Unload();
        }
    }
 
    private void ReleaseRenderTexture()
    {
        if (_renderTexture != null)
        {
            _renderTexture.Release();
            Destroy(_renderTexture);
            _renderTexture = null;
        }
    }
    
    /// <summary>
    /// 设置空状态(未加载视频时)
    /// </summary>
    private void SetEmptyState()
    {
        if (videoImage != null)
        {
            videoImage.enabled = false;
        }
    }
    
    /// <summary>
    /// 设置激活状态(视频已加载)
    /// </summary>
    private void SetActiveState()
    {
        if (videoImage != null)
        {
            videoImage.enabled = true;
        }
    }
    
    /// <summary>
    /// 验证必需组件
    /// </summary>
    private bool ValidateComponents()
    {
        if (videoPlayer == null)
        {
            Debug.LogError("UIVideoPlayer: VideoPlayer component is not assigned.");
            return false;
        }
        if (videoImage == null)
        {
            Debug.LogError("UIVideoPlayer: RawImage component is not assigned.");
            return false;
        }
        return true;
    }
 
    #endregion
 
    #region Unity Lifecycle
 
    private void Awake()
    {
        // 初始化时设置为空状态
        SetEmptyState();
    }
 
    private void OnDestroy()
    {
        Unload();
    }
 
    /// <summary>
    /// 取消预加载
    /// </summary>
    public void CancelPrepare()
    {
        if (videoPlayer == null) return;
        
        // 取消所有准备相关的事件订阅
        videoPlayer.prepareCompleted -= OnVideoPrepared;
        videoPlayer.prepareCompleted -= OnVideoPreparedForPreload;
        videoPlayer.prepareCompleted -= OnVideoPreparedForURL;
        
        // 停止 VideoPlayer(如果正在加载)
        if (_isLoading)
        {
            videoPlayer.Stop();
        }
        
        // 清理资源
        videoPlayer.clip = null;
        videoPlayer.url = null;
        videoPlayer.targetTexture = null;
        
        if (videoImage != null)
        {
            videoImage.texture = null;
        }
        
        _loadedClip = null;
        ReleaseRenderTexture();
        SetEmptyState();
        
        // 重置状态
        _isPrepared = false;
        _isLoading = false;
        
        // 触发失败回调
        _onPrepareCallback?.Invoke(false);
        _onPrepareCallback = null;
    }
 
    #endregion
}