VideoPlayer.vue
20.9 KB
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
<template>
<div class="video-player-container">
<video
v-if="useNativePlayer"
ref="nativeVideoRef"
class="video-player"
:src="videoUrlValue"
:autoplay="props.autoplay"
:muted="props.autoplay"
controls
playsinline
webkit-playsinline="true"
x5-playsinline="true"
x5-video-player-type="h5"
x5-video-player-fullscreen="true"
preload="metadata"
@play="handleNativePlay"
@pause="handleNativePause"
/>
<VideoPlayer
v-else
ref="videoRef"
:options="videoOptions"
playsinline
:class="['video-player', 'vjs-big-play-centered', { loading: !state }]"
@mounted="handleMounted"
@play="handlePlay"
@pause="handlePause"
/>
<!-- 错误提示覆盖层 -->
<div v-if="showErrorOverlay" class="error-overlay">
<div class="error-content">
<div class="error-icon">⚠️</div>
<div class="error-message">{{ errorMessage }}</div>
<button @click="retryLoad" class="retry-button">重试</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { VideoPlayer } from "@videojs-player/vue";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import { wxInfo } from "@/utils/tools"
const props = defineProps({
options: {
type: Object,
required: false,
default: () => ({}),
},
videoUrl: {
type: String,
required: true,
},
videoId: {
type: String,
required: true,
},
autoplay: {
type: Boolean,
required: false,
default: true,
},
});
const emit = defineEmits(["onPlay", "onPause"]);
const videoRef = ref(null);
const nativeVideoRef = ref(null);
const player = ref(null);
const state = ref(null);
const showErrorOverlay = ref(false);
const errorMessage = ref('');
const retryCount = ref(0);
const maxRetries = 3;
const nativeReady = ref(false);
let nativeListeners = null;
const probeInfo = ref({
ok: null,
status: null,
content_type: "",
content_length: null,
accept_ranges: "",
});
const probeLoading = ref(false);
const useNativePlayer = computed(() => {
return wxInfo().isIOSWeChat;
});
const videoUrlValue = computed(() => {
return (props.videoUrl || "").trim();
});
const formatBytes = (bytes) => {
const size = Number(bytes) || 0;
if (!size) return "";
const kb = 1024;
const mb = kb * 1024;
const gb = mb * 1024;
if (size >= gb) return (size / gb).toFixed(2) + "GB";
if (size >= mb) return (size / mb).toFixed(2) + "MB";
if (size >= kb) return (size / kb).toFixed(2) + "KB";
return String(size) + "B";
};
const getErrorHint = () => {
if (probeInfo.value.status === 403) return "(403:无权限或已过期)";
if (probeInfo.value.status === 404) return "(404:资源不存在)";
if (probeInfo.value.status && probeInfo.value.status >= 500) return `(${probeInfo.value.status}:服务器异常)`;
const len = probeInfo.value.content_length;
if (len && len >= 1024 * 1024 * 1024) {
const text = formatBytes(len);
return text ? `(文件约${text},建议 WiFi)` : "(文件较大,建议 WiFi)";
}
return "";
};
const probeVideo = async () => {
const url = videoUrlValue.value;
if (!url || typeof fetch === "undefined") return;
if (probeLoading.value) return;
probeLoading.value = true;
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
const timeoutId = setTimeout(() => controller?.abort?.(), 8000);
const setBaseInfo = (res) => {
const contentLength = res.headers.get("content-length");
probeInfo.value = {
ok: res.ok,
status: res.status,
content_type: res.headers.get("content-type") || "",
content_length: contentLength ? Number(contentLength) || null : null,
accept_ranges: res.headers.get("accept-ranges") || "",
};
};
try {
const headRes = await fetch(url, {
method: "HEAD",
mode: "cors",
cache: "no-store",
signal: controller?.signal,
});
setBaseInfo(headRes);
if (headRes.ok && probeInfo.value.content_length) return;
} catch (e) {
probeInfo.value = {
ok: null,
status: null,
content_type: "",
content_length: null,
accept_ranges: "",
};
} finally {
clearTimeout(timeoutId);
probeLoading.value = false;
}
const controller2 = typeof AbortController !== "undefined" ? new AbortController() : null;
const timeoutId2 = setTimeout(() => controller2?.abort?.(), 8000);
try {
const rangeRes = await fetch(url, {
method: "GET",
mode: "cors",
cache: "no-store",
headers: { Range: "bytes=0-1" },
signal: controller2?.signal,
});
const contentRange = rangeRes.headers.get("content-range") || "";
const match = contentRange.match(/\/(\d+)\s*$/);
const total = match ? Number(match[1]) || null : null;
const contentLength = rangeRes.headers.get("content-length");
probeInfo.value = {
ok: rangeRes.ok,
status: rangeRes.status,
content_type: rangeRes.headers.get("content-type") || "",
content_length: total || (contentLength ? Number(contentLength) || null : null),
accept_ranges: rangeRes.headers.get("accept-ranges") || "",
};
} catch (e) {
} finally {
clearTimeout(timeoutId2);
}
};
const getVideoMimeType = (url) => {
const urlText = (url || "").toLowerCase();
if (urlText.includes(".m3u8")) return "application/x-mpegURL";
if (urlText.includes(".mp4")) return "video/mp4";
if (urlText.includes(".mov")) return "video/quicktime";
return "";
};
const videoSources = computed(() => {
const type = getVideoMimeType(videoUrlValue.value);
if (type) {
return [{ src: videoUrlValue.value, type }];
}
return [{ src: videoUrlValue.value }];
});
const videoOptions = computed(() => ({
controls: true,
preload: "metadata", // 改为metadata以减少初始加载
responsive: true,
autoplay: props.autoplay,
playsinline: true,
// 启用倍速播放功能
playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2],
sources: videoSources.value,
// HTML5配置优化
html5: {
vhs: {
overrideNative: !videojs.browser.IS_SAFARI,
},
nativeVideoTracks: false,
nativeAudioTracks: false,
nativeTextTracks: false,
},
// 错误处理配置
errorDisplay: true,
// 网络和加载配置
techOrder: ['html5'],
// onPlay: () => emit("onPlay"),
// onPause: () => emit("onPause"),
userActions: {
hotkeys: true,
doubleClick: true,
},
controlBar: {
progressControl: {
seekBar: {
mouseTimeDisplay: {
keepTooltipsInside: true,
},
},
},
},
...props.options,
}));
const applyNativeError = (mediaError) => {
if (!mediaError) return;
showErrorOverlay.value = true;
switch (mediaError.code) {
case 4:
errorMessage.value = '视频格式不支持或无法加载,请检查网络连接' + getErrorHint();
if (retryCount.value < maxRetries) {
setTimeout(() => {
retryLoad();
}, 1000);
}
break;
case 3:
errorMessage.value = '视频解码失败,可能是文件损坏';
break;
case 2:
errorMessage.value = '网络连接错误,请检查网络后重试' + getErrorHint();
if (retryCount.value < maxRetries) {
setTimeout(() => {
retryLoad();
}, 2000);
}
break;
case 1:
errorMessage.value = '视频加载被中止';
break;
default:
errorMessage.value = '视频播放出现未知错误';
}
};
const handleMounted = (payload) => {
console.log('VideoPlayer: handleMounted 被调用');
console.log('VideoPlayer: payload.player:', payload.player);
state.value = payload.state;
player.value = payload.player;
if (player.value) {
// 添加错误处理监听器
player.value.on('error', (error) => {
console.error('VideoJS播放错误:', error);
const errorCode = player.value.error();
if (errorCode) {
console.error('错误代码:', errorCode.code, '错误信息:', errorCode.message);
// 显示用户友好的错误信息
showErrorOverlay.value = true;
// 根据错误类型进行处理
switch (errorCode.code) {
case 4: // MEDIA_ERR_SRC_NOT_SUPPORTED
errorMessage.value = '视频格式不支持或无法加载,请检查网络连接' + getErrorHint();
console.warn('视频格式不支持,尝试重新加载...');
// 自动重试(如果重试次数未超限)
if (retryCount.value < maxRetries) {
setTimeout(() => {
retryLoad();
}, 1000);
}
break;
case 3: // MEDIA_ERR_DECODE
errorMessage.value = '视频解码失败,可能是文件损坏';
console.warn('视频解码错误');
break;
case 2: // MEDIA_ERR_NETWORK
errorMessage.value = '网络连接错误,请检查网络后重试' + getErrorHint();
console.warn('网络错误,尝试重新加载...');
if (retryCount.value < maxRetries) {
setTimeout(() => {
retryLoad();
}, 2000);
}
break;
case 1: // MEDIA_ERR_ABORTED
errorMessage.value = '视频加载被中止';
console.warn('视频加载被中止');
break;
default:
errorMessage.value = '视频播放出现未知错误';
}
}
});
// 添加加载状态监听
player.value.on('loadstart', () => {
console.log('开始加载视频');
showErrorOverlay.value = false; // 隐藏错误提示
});
player.value.on('canplay', () => {
console.log('视频可以播放');
showErrorOverlay.value = false; // 隐藏错误提示
retryCount.value = 0; // 重置重试计数
});
player.value.on('loadedmetadata', () => {
console.log('视频元数据加载完成');
});
// TAG: 自动播放
if (props.autoplay) {
player.value.play().catch(error => {
console.warn('自动播放失败:', error);
});
}
// if (!wxInfo().isPc && !wxInfo().isWeiXinDesktop) { // 非PC端,且非微信PC端
// // 监听视频播放状态
// player.value.on('play', () => {
// // 播放时隐藏controls
// // player.value.controlBar.hide();
// });
// player.value.on('pause', () => {
// })
// // 添加touchstart事件监听
// player.value.on('touchstart', (event) => {
// // 阻止事件冒泡,避免触发controls的默认行为
// event.preventDefault();
// event.stopPropagation();
// // 检查点击位置是否在controls区域
// const controlBar = player.value.getChild('ControlBar');
// const controlBarEl = controlBar && controlBar.el();
// if (controlBarEl && controlBarEl.contains(event.target)) {
// return; // 如果点击在controls区域,不执行自定义行为
// }
// if (player.value.paused()) {
// player.value.play();
// } else {
// player.value.pause();
// }
// });
// }
}
};
const handlePlay = (payload) => {
emit("onPlay", payload)
};
const handlePause = (payload) => {
emit("onPause", payload)
}
const handleNativePlay = (event) => {
emit("onPlay", event)
};
const handleNativePause = (event) => {
emit("onPause", event)
};
const tryNativePlay = () => {
const videoEl = nativeVideoRef.value;
if (!videoEl) return;
const playPromise = videoEl.play();
if (playPromise && typeof playPromise.catch === "function") {
playPromise.catch(() => {
if (typeof window !== "undefined" && window.WeixinJSBridge) {
window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
videoEl.play().catch(() => { });
});
}
});
}
};
/**
* 重试加载视频
*/
const retryLoad = () => {
if (retryCount.value >= maxRetries) {
errorMessage.value = '重试次数已达上限,请稍后再试';
return;
}
retryCount.value++;
showErrorOverlay.value = false;
if (useNativePlayer.value) {
const videoEl = nativeVideoRef.value;
if (videoEl) {
console.log(`第${retryCount.value}次重试加载视频`);
nativeReady.value = false;
const currentSrc = videoEl.currentSrc || videoEl.src;
videoEl.pause();
videoEl.removeAttribute("src");
videoEl.load();
videoEl.src = currentSrc || videoUrlValue.value;
videoEl.load();
tryNativePlay();
}
return;
}
if (player.value && !player.value.isDisposed()) {
console.log(`第${retryCount.value}次重试加载视频`);
player.value.load();
}
};
onMounted(() => {
void probeVideo();
if (!useNativePlayer.value) return;
const videoEl = nativeVideoRef.value;
if (!videoEl) return;
const onLoadStart = () => {
showErrorOverlay.value = false;
nativeReady.value = false;
};
const onCanPlay = () => {
showErrorOverlay.value = false;
retryCount.value = 0;
nativeReady.value = true;
};
const onError = () => {
applyNativeError(videoEl.error);
};
videoEl.addEventListener("loadstart", onLoadStart);
videoEl.addEventListener("canplay", onCanPlay);
videoEl.addEventListener("error", onError);
nativeListeners = { videoEl, onLoadStart, onCanPlay, onError };
if (props.autoplay) {
tryNativePlay();
if (typeof document !== "undefined") {
document.addEventListener(
"WeixinJSBridgeReady",
() => {
tryNativePlay();
},
{ once: true }
);
}
}
});
onBeforeUnmount(() => {
if (nativeListeners?.videoEl) {
nativeListeners.videoEl.removeEventListener("loadstart", nativeListeners.onLoadStart);
nativeListeners.videoEl.removeEventListener("canplay", nativeListeners.onCanPlay);
nativeListeners.videoEl.removeEventListener("error", nativeListeners.onError);
nativeListeners = null;
}
if (videoRef.value?.$player) {
videoRef.value.$player.dispose();
}
});
watch(
() => videoUrlValue.value,
() => {
retryCount.value = 0;
showErrorOverlay.value = false;
void probeVideo();
}
);
defineExpose({
pause() {
if (useNativePlayer.value) {
try {
nativeVideoRef.value?.pause?.();
emit('onPause', nativeVideoRef.value);
} catch (e) {
console.warn('Video pause error:', e);
}
return;
}
if (player.value && !player.value.isDisposed && typeof player.value.isDisposed === 'function' && !player.value.isDisposed() && typeof player.value.pause === 'function') {
try {
player.value.pause();
emit('onPause', player.value);
} catch (e) {
console.warn('Video pause error:', e);
}
}
},
play() {
if (useNativePlayer.value) {
tryNativePlay();
return;
}
console.log('VideoPlayer: play() 被调用');
console.log('VideoPlayer: player.value:', player.value);
console.log('VideoPlayer: player.value?.isDisposed:', player.value?.isDisposed);
if (!player.value) {
console.error('VideoPlayer: player.value 不存在,播放器可能还没初始化');
return;
}
if (!player.value.isDisposed || typeof player.value.isDisposed !== 'function') {
console.error('VideoPlayer: isDisposed 方法不存在');
return;
}
if (player.value.isDisposed()) {
console.error('VideoPlayer: 播放器已被销毁');
return;
}
console.log('VideoPlayer: 尝试播放视频');
// 检查视频元素状态
try {
const tech = player.value.tech(true);
if (tech && tech.el) {
const videoEl = tech.el();
console.log('VideoPlayer: videoEl.readyState:', videoEl?.readyState, '(0=HAVE_NOTHING, 1=HAVE_METADATA, 2=HAVE_CURRENT_DATA, 3=HAVE_FUTURE_DATA, 4=HAVE_ENOUGH_DATA)');
console.log('VideoPlayer: videoEl.paused:', videoEl?.paused);
console.log('VideoPlayer: videoEl.duration:', videoEl?.duration);
console.log('VideoPlayer: videoEl.src:', videoEl?.src);
}
} catch (e) {
console.warn('VideoPlayer: 无法获取video元素:', e);
}
player.value.play()
.then(() => {
console.log('VideoPlayer: play() 成功');
})
.catch(error => {
console.error('VideoPlayer: play() 失败:', error.name, error.message);
// 如果是因为自动播放策略失败,可以静音重试
if (error.name === 'NotAllowedError') {
console.log('VideoPlayer: 浏览器阻止自动播放,尝试静音播放');
player.value.muted(true);
player.value.play()
.then(() => {
console.log('VideoPlayer: 静音播放成功');
})
.catch(err => {
console.error('VideoPlayer: 静音播放也失败:', err);
});
}
});
},
getPlayer() {
return useNativePlayer.value ? nativeVideoRef.value : player.value;
},
getId() {
return props.videoId || "meta_id";
},
});
</script>
<style scoped>
.video-player-container {
width: 100%;
height: 100%;
position: relative;
}
.video-player {
width: 100%;
height: 100%;
display: block;
aspect-ratio: 16/9;
}
.video-player.loading {
opacity: 0.6;
}
/* 错误覆盖层样式 */
.error-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.error-content {
text-align: center;
color: white;
padding: 20px;
}
.error-icon {
font-size: 48px;
margin-bottom: 16px;
}
.error-message {
font-size: 16px;
margin-bottom: 20px;
line-height: 1.5;
}
.retry-button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
.retry-button:hover {
background: #0056b3;
}
:deep(.vjs-big-play-button) {
display: none !important;
}
/* 倍速播放控件样式优化 */
:deep(.vjs-playback-rate) {
order: 7;
position: relative;
display: flex !important;
align-items: center;
z-index: 10;
margin-right: 12px;
}
/* 隐藏可能存在的图标 */
:deep(.vjs-playback-rate .vjs-icon-chapters) {
display: none !important;
}
:deep(.vjs-playback-rate .vjs-playback-rate-value) {
font-size: 1.5em;
line-height: 2;
color: #fff;
background: transparent;
border-radius: 4px;
padding: 0 8px;
margin: 0;
transition: all 0.3s ease;
cursor: pointer;
min-width: auto;
text-align: center;
width: auto;
display: inline-block;
}
:deep(.vjs-playback-rate:hover .vjs-playback-rate-value) {
background: transparent;
transform: scale(1.05);
}
/* 菜单容器优化 - 解决遮挡问题 */
:deep(.vjs-playback-rate .vjs-menu) {
background: rgba(0, 0, 0, 0.95);
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
backdrop-filter: blur(15px);
border: 1px solid rgba(255, 255, 255, 0.1);
position: absolute;
bottom: 100%;
right: 0;
margin-bottom: 8px;
min-width: 80px;
max-height: 200px;
overflow-y: auto;
z-index: 1000;
}
/* 确保菜单在视口内显示 */
:deep(.vjs-playback-rate .vjs-menu.vjs-lock-showing) {
display: block !important;
opacity: 1 !important;
visibility: visible !important;
}
:deep(.vjs-playback-rate .vjs-menu-content) {
padding: 4px 0;
}
:deep(.vjs-playback-rate .vjs-menu-item) {
color: #fff;
padding: 10px 16px;
font-size: 14px;
transition: all 0.2s ease;
border-radius: 4px;
margin: 2px 4px;
cursor: pointer;
white-space: nowrap;
text-align: center;
}
:deep(.vjs-playback-rate .vjs-menu-item:hover) {
background: rgba(255, 255, 255, 0.15);
transform: translateX(2px);
}
:deep(.vjs-playback-rate .vjs-menu-item.vjs-selected) {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
font-weight: 600;
}
/* 移动端优化 */
@media (max-width: 768px) {
:deep(.vjs-playback-rate) {
display: flex !important;
visibility: visible !important;
margin-right: 8px;
}
:deep(.vjs-playback-rate .vjs-playback-rate-value) {
font-size: 1.3em;
padding: 0 6px;
min-width: auto;
height: 36px;
line-height: 36px;
width: auto;
margin: 0;
}
:deep(.vjs-playback-rate .vjs-menu) {
min-width: 100px;
max-height: 180px;
bottom: 120%;
right: -10px;
}
:deep(.vjs-playback-rate .vjs-menu-item) {
padding: 12px 16px;
font-size: 16px;
min-height: 44px;
display: flex;
align-items: center;
justify-content: center;
}
}
/* 小屏幕设备进一步优化 */
@media (max-width: 480px) {
:deep(.vjs-playback-rate) {
margin-right: 6px;
}
:deep(.vjs-playback-rate .vjs-playback-rate-value) {
font-size: 1.2em;
padding: 0 4px;
min-width: auto;
height: 32px;
line-height: 32px;
width: auto;
margin: 0;
}
:deep(.vjs-playback-rate .vjs-menu) {
min-width: 90px;
right: -5px;
}
:deep(.vjs-playback-rate .vjs-menu-item) {
padding: 10px 12px;
font-size: 15px;
min-height: 40px;
}
}
</style>