useVideoPlayer.js
25.8 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
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { wxInfo } from '@/utils/tools'
import { buildVideoSources, canPlayHlsNatively } from './videoPlayerSource'
import { useVideoProbe } from './useVideoProbe'
import { useVideoPlaybackOverlays } from './useVideoPlaybackOverlays'
const is_safari_browser = () => {
if (typeof navigator === 'undefined') return false
const ua = navigator.userAgent || ''
const is_safari = /safari/i.test(ua) && !/chrome|crios|android|fxios|edg/i.test(ua)
return is_safari
}
/**
* - 使用方法 :您无需修改业务代码。只要传入的视频 URL 是七牛云生成的多码率 .m3u8 地址,播放器控制条右下角会自动出现“齿轮”图标,用户点击即可切换清晰度(或选择 Auto 自动切换)。
* - iOS 注意事项 :在 iOS 移动端(尤其是微信),通常使用系统原生播放器,系统会根据网速自动切换码率(ABR),但通常无法显示手动切换菜单,这是 iOS H5 的系统限制。
* - PC 和 Android 端将正常显示切换菜单。
*/
/**
* 视频播放核心逻辑 Hook
* 处理不同环境下的播放器选择、HLS支持、自动播放策略等
* @description 根据环境选择原生 video 或 video.js,并处理弱网提示、错误重试与清晰度选择等逻辑。
* @param {any} props 组件 props(需要包含 videoUrl/autoplay/useNativeOnIos/options/debug/videoId 等字段)
* @param {(event: string, ...args: any[]) => void} emit 组件 emit
* @param {import("vue").Ref<any>} videoRef videojs-player 组件 ref(用于 dispose)
* @param {import("vue").Ref<HTMLVideoElement|null>} nativeVideoRef 原生 video 元素 ref(iOS 微信)
* @returns {{
* player: import("vue").Ref<any>,
* state: import("vue").Ref<any>,
* useNativePlayer: import("vue").ComputedRef<boolean>,
* videoUrlValue: import("vue").ComputedRef<string>,
* videoOptions: import("vue").ComputedRef<any>,
* showErrorOverlay: import("vue").Ref<boolean>,
* errorMessage: import("vue").Ref<string>,
* showNetworkSpeedOverlay: import("vue").Ref<boolean>,
* networkSpeedText: import("vue").Ref<string>,
* hlsDownloadSpeedText: import("vue").Ref<string>,
* hlsSpeedDebugText: import("vue").Ref<string>,
* retryLoad: () => void,
* handleVideoJsMounted: (payload: {player: any, state: any}) => void,
* tryNativePlay: () => void
* }}
*/
export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
// 播放器实例
const player = ref(null)
const state = ref(null)
// 错误处理相关
const showErrorOverlay = ref(false)
const errorMessage = ref('')
const retryCount = ref(0)
const maxRetries = 3
const canRetry = computed(() => retryCount.value < maxRetries)
const hasEverPlayed = ref(false)
const hasStartedPlayback = ref(false)
// 原生播放器状态
const nativeReady = ref(false)
let nativeListeners = null
let retry_error_check_timer = null
// 1. 环境判断与播放器选择
const useNativePlayer = computed(() => {
// 如果 props 强制关闭原生播放器,则返回 false (使用 Video.js)
if (props.useNativeOnIos === false) {
return false
}
// 扩展逻辑:iOS 微信 + Android 微信都使用原生播放器
// 理由:微信 X5 内核对原生 <video> 支持最好,避开 Video.js 在 X5 下的兼容性问题
const info = wxInfo()
return (info.isIOS && info.isWeiXin) || (info.isAndroid && info.isWeiXin)
})
// 2. 视频源处理
const videoUrlValue = computed(() => (props.videoUrl || '').trim())
// 3. HLS 支持判断
const isM3U8 = computed(() => {
const url = videoUrlValue.value.toLowerCase()
return url.includes('.m3u8')
})
// 资源探测:只在“同源可探测”时执行,避免跨域 CORS 报错影响体验
const { probeInfo, probeVideo } = useVideoProbe(videoUrlValue)
// 视频源构造:尽可能带上 type,老设备/部分内核对 blob/部分后缀会更稳定
const videoSources = computed(() =>
buildVideoSources({
url: videoUrlValue.value,
video_id: props?.videoId,
probe_content_type: probeInfo.value.content_type,
})
)
// 播放叠层:弱网提示 + HLS 速度展示(仅 video.js + m3u8)
const {
showNetworkSpeedOverlay,
networkSpeedText,
hlsDownloadSpeedText,
hlsSpeedDebugText,
setHlsDebug,
showNetworkSpeed,
hideNetworkSpeed,
startHlsDownloadSpeed,
stopHlsDownloadSpeed,
disposeOverlays,
} = useVideoPlaybackOverlays({
props,
player,
is_m3u8: isM3U8,
use_native_player: useNativePlayer,
show_error_overlay: showErrorOverlay,
has_started_playback: hasStartedPlayback,
})
// 6. 错误处理逻辑
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 ''
}
// 7. 错误处理逻辑
const handleError = (code, message = '') => {
showErrorOverlay.value = true
hideNetworkSpeed()
// 调试日志:记录错误
if (props.debug) {
console.group('❌ [VideoPlayer] 播放错误')
console.error('错误代码:', code)
console.error('错误信息:', message || errorMessage.value)
console.error('视频 URL:', videoUrlValue.value)
console.error('重试次数:', `${retryCount.value}/${maxRetries}`)
console.groupEnd()
}
switch (code) {
case 4: // MEDIA_ERR_SRC_NOT_SUPPORTED
errorMessage.value = `视频格式不支持或无法加载,请检查网络连接${getErrorHint()}`
// 旧机型/弱网下可能出现短暂的”无法加载”,这里做有限次数重试
// if (retryCount.value < maxRetries) {
// setTimeout(retryLoad, 1000);
// }
break
case 3: // MEDIA_ERR_DECODE
errorMessage.value = '视频解码失败,可能是文件损坏'
break
case 2: // MEDIA_ERR_NETWORK
errorMessage.value = `网络连接错误,请检查网络后重试${getErrorHint()}`
if (retryCount.value < maxRetries) {
if (props.debug) {
console.log('🔄 [VideoPlayer] 2秒后自动重试...')
}
setTimeout(retryLoad, 2000)
}
break
case 1: // MEDIA_ERR_ABORTED
errorMessage.value = '视频加载被中止'
break
default:
errorMessage.value = message || '视频播放出现未知错误'
}
}
// 4. 原生播放器逻辑 (iOS微信)
const initNativePlayer = () => {
const videoEl = nativeVideoRef.value
if (!videoEl) return
setHlsDebug('native:init')
// 原生播放器走系统内核:事件主要用于控制弱网提示与错误覆盖层
const onLoadStart = () => {
showErrorOverlay.value = false
nativeReady.value = false
}
const onCanPlay = () => {
showErrorOverlay.value = false
retryCount.value = 0
nativeReady.value = true
}
const onError = () => {
handleError(videoEl.error?.code)
}
const onPlay = () => {
hideNetworkSpeed()
setHlsDebug('native:play')
}
const onPause = () => {
hideNetworkSpeed()
}
const onWaiting = () => {
if (videoEl.paused) return
showNetworkSpeed()
setHlsDebug('native:waiting')
}
const onStalled = () => {
if (videoEl.paused) return
showNetworkSpeed()
setHlsDebug('native:stalled')
}
const onPlaying = () => {
hasEverPlayed.value = true
hasStartedPlayback.value = true
hideNetworkSpeed()
setHlsDebug('native:playing')
}
videoEl.addEventListener('loadstart', onLoadStart)
videoEl.addEventListener('canplay', onCanPlay)
videoEl.addEventListener('error', onError)
videoEl.addEventListener('play', onPlay)
videoEl.addEventListener('pause', onPause)
videoEl.addEventListener('waiting', onWaiting)
videoEl.addEventListener('stalled', onStalled)
videoEl.addEventListener('playing', onPlaying)
nativeListeners = {
videoEl,
onLoadStart,
onCanPlay,
onError,
onPlay,
onPause,
onWaiting,
onStalled,
onPlaying,
}
if (props.autoplay) {
// iOS 微信 autoplay 需要用户手势/桥接事件配合,先尝试一次,再在 WeixinJSBridgeReady 时再试
tryNativePlay()
if (typeof document !== 'undefined') {
document.addEventListener('WeixinJSBridgeReady', () => tryNativePlay(), { once: true })
}
}
}
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(() => {})
})
}
})
}
}
// 5. Video.js 播放器逻辑 (PC/Android)
const shouldOverrideNativeHls = computed(() => {
if (!isM3U8.value) return false
if (is_safari_browser()) return false
// 非 Safari 且不具备原生 HLS 时,强制 video.js 的 VHS 来解 m3u8
return !canPlayHlsNatively()
})
const videoOptions = computed(() => {
const base = {
controls: true,
preload: 'metadata',
responsive: true,
autoplay: props.autoplay,
playsinline: true,
playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2],
sources: videoSources.value,
html5: {
vhs: {
overrideNative: shouldOverrideNativeHls.value,
// 优化跨域视频加载配置
enableLowInitialPlaylist: true,
// 增加 VHS 超时时间(默认 30 秒,增加到 60 秒)
handleManifestRedirects: true,
// 配置 VHS 超时和重试
blacklistDuration: Infinity,
// 允许重试失败的分段
handleManifestRedirects: true,
},
nativeVideoTracks: false,
nativeAudioTracks: false,
nativeTextTracks: false,
hls: {
withCredentials: false,
// HLS 配置
overrideNative: shouldOverrideNativeHls.value,
},
// 配置原生视频请求超时和重试
requestMediaAccessPermissions: false,
},
techOrder: ['html5'],
userActions: {
hotkeys: true,
doubleClick: true,
},
controlBar: {
progressControl: {
seekBar: {
mouseTimeDisplay: {
keepTooltipsInside: true,
},
},
},
},
// 增加网络超时配置(跨域大视频需要更长的超时时间)
// 这会影响 video.js 内部 XHR 的超时
...props.options,
errorDisplay: false,
}
if (!base.poster) {
delete base.poster
}
return base
})
// 8. Video.js 挂载处理
const handleVideoJsMounted = payload => {
state.value = payload.state
player.value = payload.player
// 调试日志:Video.js 挂载成功
if (props.debug) {
console.group('🎬 [VideoPlayer] Video.js 挂载成功')
console.log('📦 播放器实例:', player.value)
console.log('🎯 当前视频源:', videoSources.value)
console.log('🌐 是否 HLS:', isM3U8.value)
console.log('🔧 覆盖原生 HLS:', shouldOverrideNativeHls.value)
console.groupEnd()
}
if (player.value) {
setHlsDebug('mounted')
// 添加详细的加载事件监听
if (props.debug) {
console.log('🔧 [VideoPlayer] 开始监听视频加载事件...')
const events = [
'loadstart', // 开始加载
'loadedmetadata', // 元数据加载完成
'loadeddata', // 数据加载完成
'canplay', // 可以播放
'canplaythrough', // 可以流畅播放
'playing', // 正在播放
'waiting', // 等待数据
'stalled', // 网络卡顿
'suspend', // 暂停加载
'progress', // 加载进度
'durationchange', // 时长变化
'volumechange', // 音量变化
'ratechange', // 播放速率变化
]
events.forEach(eventName => {
player.value.on(eventName, () => {
console.log(`📡 [VideoPlayer] 事件触发: ${eventName}`)
})
})
// 监听网络状态变化
player.value.on('networkstate', () => {
try {
const networkState = player.value.currentSrc() ? '已连接' : '未连接'
console.log(`🌐 [VideoPlayer] 网络状态: ${networkState}`)
} catch (e) {
console.log(`🌐 [VideoPlayer] 网络状态变化`)
}
})
// 监听就绪状态
player.value.on('readystate', () => {
try {
const readyState = player.value.readyState()
const states = [
'HAVE_NOTHING',
'HAVE_METADATA',
'HAVE_CURRENT_DATA',
'HAVE_FUTURE_DATA',
'HAVE_ENOUGH_DATA',
]
console.log(`📊 [VideoPlayer] 就绪状态: ${states[readyState] || readyState}`)
} catch (e) {
console.log(`📊 [VideoPlayer] 就绪状态变化`)
}
})
// 监听缓冲进度
const checkBuffer = () => {
try {
const buffered = player.value.buffered()
const duration = player.value.duration() || 0
if (buffered && buffered.length > 0) {
const bufferedEnd = buffered.end(buffered.length - 1)
const bufferedPercent =
duration > 0 ? ((bufferedEnd / duration) * 100).toFixed(2) : '0.00'
console.log(
`📊 [VideoPlayer] 缓冲进度: ${bufferedPercent}% (${bufferedEnd.toFixed(2)}s / ${duration.toFixed(2)}s)`
)
// 检查缓冲是否卡住(5秒内没有增长)
const now = Date.now()
if (!checkBuffer.lastBufferTime) {
checkBuffer.lastBufferTime = now
checkBuffer.lastBufferEnd = bufferedEnd
} else {
const timeDiff = (now - checkBuffer.lastBufferTime) / 1000
const bufferDiff = bufferedEnd - checkBuffer.lastBufferEnd
if (timeDiff > 5 && bufferDiff === 0 && bufferedEnd < duration) {
console.warn(`⚠️ [VideoPlayer] 缓冲已卡住 ${timeDiff.toFixed(1)} 秒!`)
console.warn(
` 当前缓冲: ${bufferedEnd.toFixed(2)}s, 总时长: ${duration.toFixed(2)}s`
)
console.warn(` 可能原因: 网络中断、CDN限制、或视频源问题`)
}
// 如果缓冲有增长,更新时间戳
if (bufferDiff > 0) {
checkBuffer.lastBufferTime = now
checkBuffer.lastBufferEnd = bufferedEnd
}
}
}
} catch (e) {
// 忽略错误
}
}
// 定期检查缓冲进度
const bufferInterval = setInterval(() => {
if (player.value && !player.value.isDisposed()) {
checkBuffer()
} else {
clearInterval(bufferInterval)
}
}, 2000)
// 播放器销毁时清除定时器
const originalDispose = player.value.dispose
player.value.dispose = function () {
clearInterval(bufferInterval)
return originalDispose.call(this)
}
// 立即检查一次
setTimeout(checkBuffer, 100)
// 使用 Performance API 监控网络请求
setTimeout(() => {
try {
const perfEntries = performance.getEntriesByType('resource')
const videoRequests = perfEntries.filter(entry => {
const url = entry.name?.toLowerCase() || ''
return url.includes('.mp4') || url.includes('.m3u8') || url.includes('cdn')
})
if (videoRequests.length > 0) {
console.group('🌐 [VideoPlayer] 网络请求监控')
videoRequests.forEach((req, index) => {
console.log(`请求 #${index + 1}:`)
console.log(' URL:', req.name)
console.log(
' 状态:',
'transferSize' in req
? req.transferSize > 0
? '✅ 成功'
: '⚠️ 可能为空'
: '未知'
)
console.log(' 传输大小:', (req.transferSize / 1024 / 1024).toFixed(2), 'MB')
console.log(' 编码大小:', (req.encodedBodySize / 1024 / 1024).toFixed(2), 'MB')
console.log(' 解码大小:', (req.decodedBodySize / 1024 / 1024).toFixed(2), 'MB')
console.log(' 持续时间:', (req.duration / 1000).toFixed(2), '秒')
console.log(
' 是否完整:',
req.transferSize === req.encodedBodySize ? '是' : '否(可能中断)'
)
// 检查是否被中断
if (req.transferSize > 0 && req.transferSize < req.encodedBodySize) {
console.error('❌ 请求可能被中断!')
}
})
console.groupEnd()
}
} catch (e) {
console.log('🌐 [VideoPlayer] Performance API 不可用')
}
}, 3000) // 3秒后检查请求状态
}
const quality_selector_inited = { value: false }
const setupQualitySelector = () => {
if (quality_selector_inited.value) return
if (!isM3U8.value) return
const p = player.value
if (!p || (typeof p.isDisposed === 'function' && p.isDisposed())) return
if (typeof p.hlsQualitySelector !== 'function') return
if (typeof p.qualityLevels !== 'function') return
let tech = null
try {
tech = typeof p.tech === 'function' ? p.tech({ IWillNotUseThisInPlugins: true }) : null
} catch (e) {
tech = null
}
if (!tech) return
// videojs-hls-quality-selector 旧版本依赖 tech.hls,而 video.js 7 默认是 tech.vhs,这里做兼容别名
if (!tech.hls && tech.vhs) {
try {
tech.hls = tech.vhs
} catch (e) {
void e
}
}
if (!tech.hls) return
try {
p.hlsQualitySelector({
displayCurrentQuality: true,
})
quality_selector_inited.value = true
} catch (e) {
void e
}
}
setupQualitySelector()
player.value.on('error', () => {
const err = player.value.error()
handleError(err?.code, err?.message)
})
player.value.on('loadstart', () => {
showErrorOverlay.value = false
setupQualitySelector()
})
player.value.on('canplay', () => {
showErrorOverlay.value = false
retryCount.value = 0
setupQualitySelector()
})
player.value.on('play', () => {
hideNetworkSpeed()
startHlsDownloadSpeed()
setHlsDebug('play')
})
player.value.on('pause', () => {
hideNetworkSpeed()
stopHlsDownloadSpeed('pause')
setHlsDebug('pause')
})
player.value.on('waiting', () => {
if (!hasEverPlayed.value) return
if (player.value?.paused?.()) return
// 已经播放过且当前未暂停,才认为是“卡顿等待”,显示弱网提示
showNetworkSpeed()
startHlsDownloadSpeed()
setHlsDebug('waiting')
})
player.value.on('stalled', () => {
if (!hasEverPlayed.value) return
if (player.value?.paused?.()) return
showNetworkSpeed()
startHlsDownloadSpeed()
setHlsDebug('stalled')
})
player.value.on('playing', () => {
hasEverPlayed.value = true
hasStartedPlayback.value = true
hideNetworkSpeed()
setHlsDebug('playing')
})
player.value.on('ended', () => {
stopHlsDownloadSpeed('ended')
setHlsDebug('ended')
})
if (props.autoplay) {
if (props.debug) {
console.log('▶️ [VideoPlayer] 尝试自动播放')
}
player.value
.play()
.then(() => {
if (props.debug) {
console.log('✅ [VideoPlayer] 自动播放成功')
}
})
.catch(err => {
if (props.debug) {
console.error('❌ [VideoPlayer] 自动播放失败:', err)
console.error(' 失败原因:', err.name)
console.error(' 错误消息:', err.message)
}
})
}
}
}
// 6. 重试逻辑
const retryLoad = () => {
if (!canRetry.value) {
showErrorOverlay.value = true
return
}
retryCount.value++
showErrorOverlay.value = false
hideNetworkSpeed()
stopHlsDownloadSpeed('retry')
if (retry_error_check_timer) {
clearTimeout(retry_error_check_timer)
retry_error_check_timer = null
}
if (useNativePlayer.value) {
// 原生 video 需要手动重置 src/load
const videoEl = nativeVideoRef.value
if (videoEl) {
nativeReady.value = false
const currentSrc = videoEl.currentSrc || videoEl.src
videoEl.pause()
videoEl.removeAttribute('src')
videoEl.load()
videoEl.src = currentSrc || videoUrlValue.value
videoEl.load()
tryNativePlay()
retry_error_check_timer = setTimeout(() => {
const err_code = videoEl?.error?.code
if (err_code) {
handleError(err_code)
}
}, 800)
}
} else {
// video.js 走自身 load 刷新
if (player.value && !player.value.isDisposed()) {
const p = player.value
try {
p.pause?.()
} catch (e) {
void e
}
try {
p.error?.(null)
} catch (e) {
void e
}
try {
p.src?.(videoSources.value)
} catch (e) {
void e
}
try {
p.load?.()
} catch (e) {
void e
}
try {
p.play?.()?.catch?.(() => {})
} catch (e) {
void e
}
retry_error_check_timer = setTimeout(() => {
const err = p?.error?.()
if (err?.code) {
handleError(err.code, err.message)
}
}, 800)
}
}
}
// 7. 生命周期与监听
watch(
() => videoUrlValue.value,
() => {
retryCount.value = 0
showErrorOverlay.value = false
hideNetworkSpeed()
stopHlsDownloadSpeed('url_change')
hasEverPlayed.value = false
hasStartedPlayback.value = false
// 地址变更后刷新探测信息,错误提示会基于 probeInfo 补充更准确的原因
void probeVideo()
// 如果是原生播放器且 URL 变化,需要手动处理 HLS (如果是非 iOS Safari 环境)
if (useNativePlayer.value && isM3U8.value) {
// iOS 原生支持,不需要额外操作
// 如果未来支持 Android 原生播放器且不支持 HLS,需在此处初始化 hls.js
}
}
)
onMounted(() => {
// 调试日志:组件挂载
if (props.debug) {
console.group('🎬 [VideoPlayer] 组件挂载')
console.log('📹 视频 URL:', videoUrlValue.value)
console.log('🎥 播放器类型:', useNativePlayer.value ? '原生播放器' : 'Video.js')
console.log('🌐 是否 HLS:', isM3U8.value)
console.groupEnd()
}
void probeVideo()
if (useNativePlayer.value) {
initNativePlayer()
}
})
onBeforeUnmount(() => {
// 调试日志:组件卸载
if (props.debug) {
console.log('🗑️ [VideoPlayer] 组件卸载,清理播放器资源')
}
if (retry_error_check_timer) {
clearTimeout(retry_error_check_timer)
retry_error_check_timer = null
}
if (nativeListeners?.videoEl) {
nativeListeners.videoEl.removeEventListener('loadstart', nativeListeners.onLoadStart)
nativeListeners.videoEl.removeEventListener('canplay', nativeListeners.onCanPlay)
nativeListeners.videoEl.removeEventListener('error', nativeListeners.onError)
nativeListeners.videoEl.removeEventListener('play', nativeListeners.onPlay)
nativeListeners.videoEl.removeEventListener('pause', nativeListeners.onPause)
nativeListeners.videoEl.removeEventListener('waiting', nativeListeners.onWaiting)
nativeListeners.videoEl.removeEventListener('stalled', nativeListeners.onStalled)
nativeListeners.videoEl.removeEventListener('playing', nativeListeners.onPlaying)
}
disposeOverlays()
if (videoRef.value?.$player) {
videoRef.value.$player.dispose()
}
})
return {
player,
state,
useNativePlayer,
videoUrlValue,
videoOptions,
showErrorOverlay,
errorMessage,
canRetry,
retryCount,
maxRetries,
showNetworkSpeedOverlay,
networkSpeedText,
hlsDownloadSpeedText,
hlsSpeedDebugText,
retryLoad,
handleVideoJsMounted,
tryNativePlay,
}
}