-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathArtVideoPlayer.vue
More file actions
1714 lines (1480 loc) · 45.7 KB
/
ArtVideoPlayer.vue
File metadata and controls
1714 lines (1480 loc) · 45.7 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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<template>
<a-card v-if="visible && videoUrl" class="video-player-section">
<PlayerHeader
:episode-name="episodeName"
:player-type="playerType"
:episodes="episodes"
:auto-next-enabled="autoNextEnabled"
:countdown-enabled="countdownEnabled"
:skip-enabled="skipEnabled"
@toggle-auto-next="toggleAutoNext"
@toggle-countdown="toggleCountdown"
@player-change="handlePlayerTypeChange"
@open-skip-settings="openSkipSettingsDialog"
@close="closePlayer"
/>
<div class="art-player-wrapper" v-show="props.visible">
<div ref="artPlayerContainer" class="art-player-container">
<!-- ArtPlayer 将在这里初始化 -->
</div>
<!-- 自动下一集倒计时弹窗 -->
<div v-if="showAutoNextDialog" class="auto-next-dialog">
<div class="auto-next-content">
<div class="auto-next-title">
<span>即将播放下一集</span>
</div>
<div class="auto-next-episode" v-if="getNextEpisode()">
{{ getNextEpisode().name }}
</div>
<div class="auto-next-countdown">
{{ autoNextCountdown }} 秒后自动播放
</div>
<div class="auto-next-buttons">
<button @click="playNextEpisode" class="btn-play-now">立即播放</button>
<button @click="cancelAutoNext" class="btn-cancel">取消</button>
</div>
</div>
</div>
<!-- 片头片尾设置弹窗 -->
<SkipSettingsDialog
:visible="showSkipSettingsDialog"
:skip-intro-enabled="skipIntroEnabled"
:skip-outro-enabled="skipOutroEnabled"
:skip-intro-seconds="skipIntroSeconds"
:skip-outro-seconds="skipOutroSeconds"
@close="closeSkipSettingsDialog"
@save="saveSkipSettings"
/>
</div>
</a-card>
</template>
<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconClose } from '@arco-design/web-vue/es/icon'
import Artplayer from 'artplayer'
import Hls from 'hls.js'
// 配置自定义倍速选项
Artplayer.PLAYBACK_RATE = [0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 4, 5]
import PlayerHeader from './PlayerHeader.vue'
import SkipSettingsDialog from './SkipSettingsDialog.vue'
import { useSkipSettings } from '@/composables/useSkipSettings'
import { applyCSPBypass, setVideoReferrerPolicy, REFERRER_POLICIES } from '@/utils/csp'
// Props - 已添加 HLS 支持、动态高度自适应和自动下一集功能
const props = defineProps({
visible: {
type: Boolean,
default: false
},
videoUrl: {
type: String,
default: ''
},
episodeName: {
type: String,
default: '未知选集'
},
poster: {
type: String,
default: ''
},
playerType: {
type: String,
default: 'artplayer'
},
// 自动下一集功能相关 props
episodes: {
type: Array,
default: () => []
},
currentEpisodeIndex: {
type: Number,
default: 0
},
autoNext: {
type: Boolean,
default: true
}
})
// Emits
const emit = defineEmits(['close', 'error', 'player-change', 'next-episode', 'episode-selected'])
// 响应式数据
const artPlayerContainer = ref(null)
const artPlayerInstance = ref(null)
const retryCount = ref(0) // 重连次数计数器
const maxRetries = ref(3) // 最大重连次数
const isRetrying = ref(false) // 是否正在重连
const dynamicHeight = ref(450) // 动态计算的高度
// 自动下一集功能相关数据
const autoNextEnabled = ref(true) // 自动下一集开关,默认关闭
const autoNextCountdown = ref(0) // 自动下一集倒计时
const autoNextTimer = ref(null) // 自动下一集定时器
const showAutoNextDialog = ref(false) // 显示自动下一集对话框
const countdownEnabled = ref(false) // 倒计时开关,默认关闭
// 选集弹窗相关数据已移除,现在使用ArtPlayer的layer功能
// 使用片头片尾设置组合式函数
const {
showSkipSettingsDialog,
skipIntroEnabled,
skipOutroEnabled,
skipIntroSeconds,
skipOutroSeconds,
skipEnabled,
initSkipSettings,
resetSkipState,
applySkipSettings,
applyIntroSkipImmediate,
handleTimeUpdate,
closeSkipSettingsDialog,
saveSkipSettings: saveSkipSettingsComposable,
onUserSeekStart,
onUserSeekEnd,
onFullscreenChangeStart,
onFullscreenChangeEnd
} = useSkipSettings({
onSkipToNext: () => {
if (autoNextEnabled.value && hasNextEpisode()) {
playNextEpisode()
}
},
getCurrentTime: () => artPlayerInstance.value?.video?.currentTime || 0,
setCurrentTime: (time) => {
if (artPlayerInstance.value?.video) {
artPlayerInstance.value.video.currentTime = time
}
},
getDuration: () => artPlayerInstance.value?.video?.duration || 0
})
// 链接类型判断函数
const isDirectVideoLink = (url) => {
if (!url) return false
// 视频文件扩展名
const videoExtensions = [
'.mp4', '.webm', '.ogg', '.avi', '.mov', '.wmv', '.flv', '.mkv',
'.m4v', '.3gp', '.ts', '.m3u8', '.mpd'
]
// 检查URL是否包含视频扩展名
const hasVideoExtension = videoExtensions.some(ext =>
url.toLowerCase().includes(ext)
)
// 检查是否是流媒体格式
const isStreamingFormat = url.toLowerCase().includes('m3u8') ||
url.toLowerCase().includes('mpd') ||
url.toLowerCase().includes('rtmp') ||
url.toLowerCase().includes('rtsp')
// 如果有视频扩展名或是流媒体格式,认为是直链
if (hasVideoExtension || isStreamingFormat) {
return true
}
// 检查是否看起来像网页链接(但排除已经确认为视频的情况)
const looksLikeWebpage = url.includes('://') &&
(url.includes('.html') ||
url.includes('.php') ||
url.includes('.asp') ||
url.includes('.jsp') ||
url.match(/\/[^.?#]*$/) // 没有扩展名且没有查询参数的路径
) &&
!hasVideoExtension &&
!isStreamingFormat
// 如果看起来像网页,认为不是直链
if (looksLikeWebpage) {
return false
}
// 默认尝试作为直链处理
return true
}
// 初始化 ArtPlayer
const initArtPlayer = async (url) => {
if (!artPlayerContainer.value || !url) return
console.log('初始化 ArtPlayer:', url)
// 应用CSP绕过策略
try {
const appliedPolicy = applyCSPBypass(url)
console.log(`已为ArtPlayer应用CSP策略: ${appliedPolicy}`)
} catch (error) {
console.warn('应用CSP策略失败:', error)
}
// 重置重连状态
resetRetryState()
// 重置片头片尾状态
resetSkipState()
// 等待 DOM 更新后计算动态高度
await nextTick()
dynamicHeight.value = calculateDynamicHeight()
// 应用动态高度到容器
artPlayerContainer.value.style.height = `${dynamicHeight.value}px`
// 首先判断链接类型
if (!isDirectVideoLink(url)) {
console.log('检测到网页链接,在新窗口打开:', url)
Message.info('检测到网页链接,正在新窗口打开...')
window.open(url, '_blank')
emit('close') // 关闭播放器
return
}
// 如果播放器实例已存在,使用 switchUrl 方法切换视频源
if (artPlayerInstance.value) {
console.log('使用 switchUrl 方法切换视频源:', url)
try {
// 使用 switchUrl 方法切换视频源,这样可以保持全屏状态和其他用户设置
await artPlayerInstance.value.switchUrl(url)
console.log('视频源切换成功')
// 重新应用片头片尾设置
applySkipSettings()
return // 切换成功,直接返回
} catch (error) {
console.error('switchUrl 切换失败,回退到销毁重建方式:', error)
// 如果 switchUrl 失败,回退到原来的销毁重建方式
// 清理缓冲区清理定时器
if (artPlayerInstance.value.bufferCleanupInterval) {
clearInterval(artPlayerInstance.value.bufferCleanupInterval)
artPlayerInstance.value.bufferCleanupInterval = null
}
// 清理 HLS 实例
if (artPlayerInstance.value.hls) {
artPlayerInstance.value.hls.destroy()
artPlayerInstance.value.hls = null
}
artPlayerInstance.value.destroy()
artPlayerInstance.value = null
}
}
try {
// 检查是否为 HLS 流
const isHLS = url.includes('.m3u8') || url.includes('m3u8')
// 创建 ArtPlayer 实例
const art = new Artplayer({
container: artPlayerContainer.value,
url: url,
poster: props.poster,
volume: 0.7,
isLive: false,
muted: false,
autoplay: true,
pip: true,
autoSize: false,
autoMini: true,
width: '100%',
height: dynamicHeight.value,
screenshot: true,
setting: true,
loop: false,
flip: true,
playbackRate: true,
aspectRatio: true,
fullscreen: true,
fullscreenWeb: true,
subtitleOffset: true,
miniProgressBar: true,
mutex: true,
backdrop: true,
playsInline: true,
autoPlayback: true,
airplay: true,
theme: '#23ade5',
lang: 'zh-cn',
whitelist: ['*'],
// 移除crossOrigin设置以避免CORS问题
// moreVideoAttr: {
// crossOrigin: 'anonymous',
// },
// 自定义视频类型处理
type: isHLS ? 'm3u8' : '',
// 自定义加载器
customType: isHLS ? {
m3u8: function (video, url, art) {
if (Hls.isSupported()) {
const hls = new Hls({
// HLS 配置选项
enableWorker: true,
lowLatencyMode: false, // 关闭低延迟模式,提高稳定性
// 缓冲区配置 - 关键优化
backBufferLength: 15, // 减少后缓冲长度,避免内存占用过多
maxBufferLength: 30, // 减少最大缓冲长度到30秒,避免内存问题
maxBufferSize: 30 * 1000 * 1000, // 减少最大缓冲大小到30MB
maxBufferHole: 0.3, // 减少最大缓冲空洞到0.3秒
// 网络配置
maxLoadingDelay: 3, // 减少最大加载延迟到3秒
maxRetryDelay: 6, // 减少最大重试延迟到6秒
maxRetry: 2, // 减少最大重试次数到2次,避免过度重试
// 片段配置
fragLoadingTimeOut: 15000, // 减少片段加载超时到15秒
manifestLoadingTimeOut: 8000, // 减少清单加载超时到8秒
fragLoadingMaxRetry: 2, // 片段加载最大重试次数
manifestLoadingMaxRetry: 2, // 清单加载最大重试次数
// 启用自动质量切换
enableSoftwareAES: true,
startLevel: -1, // 自动选择起始质量
capLevelToPlayerSize: true, // 根据播放器大小限制质量
// 错误恢复配置
liveSyncDurationCount: 3,
liveMaxLatencyDurationCount: Infinity,
liveDurationInfinity: false,
// 新增配置项,提高稳定性
nudgeOffset: 0.1, // 微调偏移量
nudgeMaxRetry: 3, // 微调最大重试次数
maxSeekHole: 2, // 最大寻址空洞
// 调试配置(生产环境可关闭)
debug: false,
})
hls.loadSource(url)
hls.attachMedia(video)
// 存储 hls 实例到 art 对象上,方便后续清理
art.hls = hls
// HLS 事件监听
hls.on(Hls.Events.MANIFEST_PARSED, () => {
console.log('HLS manifest 解析完成')
})
// 错误重试计数器
let networkErrorRetries = 0
let mediaErrorRetries = 0
const maxErrorRetries = 2 // 减少重试次数
hls.on(Hls.Events.ERROR, (event, data) => {
// 只记录致命错误,减少控制台噪音
if (data.fatal) {
console.error('HLS 致命错误:', data.type, data.details)
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
networkErrorRetries++
if (networkErrorRetries <= maxErrorRetries) {
console.log(`网络错误恢复中... (${networkErrorRetries}/${maxErrorRetries})`)
// 延迟重试,避免频繁请求
setTimeout(() => {
hls.startLoad()
}, 1000 * networkErrorRetries) // 递增延迟
} else {
console.error('网络错误重试次数超限')
Message.error('网络连接不稳定,请检查网络后重试')
hls.destroy()
}
break
case Hls.ErrorTypes.MEDIA_ERROR:
mediaErrorRetries++
if (mediaErrorRetries <= maxErrorRetries) {
console.log(`媒体错误恢复中... (${mediaErrorRetries}/${maxErrorRetries})`)
setTimeout(() => {
hls.recoverMediaError()
}, 500 * mediaErrorRetries) // 递增延迟
} else {
console.error('媒体错误恢复次数超限')
Message.error('视频解码错误,请尝试刷新页面')
hls.destroy()
}
break
default:
// 对于其他致命错误,不显示用户提示,只记录日志
console.error('无法恢复的HLS错误:', data.details)
hls.destroy()
break
}
} else {
// 非致命错误,只在调试模式下记录
if (data.details !== 'bufferAppendError' && data.details !== 'bufferStalledError') {
console.debug('HLS 非致命错误:', data.details)
}
// 对于缓冲区错误,尝试自动恢复
if (data.details === 'bufferStalledError') {
console.debug('检测到缓冲停滞,自动处理中...')
// HLS.js 会自动处理这类错误,无需手动干预
}
}
})
// 监听缓冲区事件,用于性能优化
hls.on(Hls.Events.BUFFER_APPENDED, () => {
// 缓冲区数据追加成功,可以在这里做一些清理工作
})
hls.on(Hls.Events.BUFFER_EOS, () => {
console.debug('缓冲区到达流结束')
})
// 监听缓冲区清理事件
hls.on(Hls.Events.BUFFER_FLUSHED, () => {
console.debug('缓冲区已清理')
})
// 重置错误计数器(当播放成功时)
hls.on(Hls.Events.FRAG_LOADED, () => {
// 片段加载成功,重置错误计数
if (networkErrorRetries > 0 || mediaErrorRetries > 0) {
console.log('连接恢复正常,重置错误计数器')
networkErrorRetries = 0
mediaErrorRetries = 0
}
})
// 监听质量切换事件
hls.on(Hls.Events.LEVEL_SWITCHED, (event, data) => {
console.debug(`质量切换到: ${data.level}`)
})
// 定期清理缓冲区,避免内存占用过多
let bufferCleanupInterval = setInterval(() => {
if (hls && video && !video.paused) {
const currentTime = video.currentTime
// 清理当前播放位置前15秒以外的缓冲区
if (currentTime > 15) {
try {
hls.trigger(Hls.Events.BUFFER_FLUSHING, {
startOffset: 0,
endOffset: currentTime - 15,
type: 'video'
})
} catch (e) {
console.debug('缓冲区清理失败:', e)
}
}
}
}, 30000) // 每30秒清理一次
// 存储清理定时器,用于后续清理
art.bufferCleanupInterval = bufferCleanupInterval
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Safari 原生支持 HLS
video.src = url
} else {
console.error('此浏览器不支持 HLS 播放')
Message.error('此浏览器不支持 HLS 播放')
}
}
} : {},
// 自定义控制栏
controls: [
{
position: 'right',
html: hasNextEpisode() ? '下一集' : '',
tooltip: hasNextEpisode() ? '播放下一集' : '',
style: hasNextEpisode() ? {} : { display: 'none' },
click: function () {
playNextEpisode()
},
},
{
position: 'right',
html: props.episodes.length > 1 ? '选集' : '',
tooltip: props.episodes.length > 1 ? '选择集数' : '',
style: props.episodes.length > 1 ? {} : { display: 'none' },
click: function () {
toggleEpisodeLayer()
},
},
{
position: 'right',
html: '关闭',
tooltip: '关闭播放器',
click: function () {
closePlayer()
},
},
],
// 质量选择器(如果支持)
quality: [],
// 字幕配置
subtitle: {
url: '',
type: 'srt',
encoding: 'utf-8',
escape: true,
},
// 右键菜单
contextmenu: [
{
html: '自定义菜单',
click: function () {
console.log('点击了自定义菜单')
},
},
],
// 图层配置
layers: [
{
name: 'episodeLayer',
html: '',
style: {
position: 'absolute',
top: '0',
left: '0',
width: '100%',
height: '100%',
background: 'rgba(0, 0, 0, 0.8)',
display: 'none',
zIndex: '100',
padding: '0',
boxSizing: 'border-box',
overflow: 'hidden'
},
click: function(event) {
// 点击背景关闭layer
if (event.target.classList.contains('episode-layer-background')) {
hideEpisodeLayer()
}
}
}
],
// 插件配置
plugins: [],
})
// 事件监听
art.on('ready', () => {
console.log('ArtPlayer 准备就绪')
// 应用片头片尾设置
applySkipSettings()
})
art.on('video:loadstart', () => {
// 重置片头片尾跳过状态
resetSkipState()
})
art.on('video:canplay', () => {
// 视频可以播放时,重置重连计数器
resetRetryState()
// 应用片头片尾设置
applySkipSettings()
})
art.on('video:timeupdate', () => {
handleTimeUpdate()
})
// 监听用户拖动进度条事件
art.on('video:seeking', () => {
onUserSeekStart()
})
art.on('video:seeked', () => {
onUserSeekEnd()
})
art.on('video:playing', () => {
// 视频开始播放时,重置重连计数器
resetRetryState()
// 立即尝试片头跳过(针对视频刚开始播放的情况)
const immediateSkipped = applyIntroSkipImmediate()
// 如果立即跳过未执行,则使用常规跳过逻辑
if (!immediateSkipped) {
applySkipSettings()
// 为了确保片头跳过生效,再次检查(短延迟)
setTimeout(() => {
applySkipSettings()
}, 50) // 减少延迟到50ms
}
})
// 监听全屏状态变化
art.on('fullscreen', (isFullscreen) => {
// 标记全屏状态开始变化
onFullscreenChangeStart()
// 500ms后标记全屏状态变化结束
setTimeout(() => {
onFullscreenChangeEnd()
}, 500)
})
art.on('video:error', (err) => {
console.error('ArtPlayer 播放错误:', err)
// 如果播放失败,再次检查是否为网页链接
if (!isDirectVideoLink(url)) {
console.log('播放失败,检测到可能是网页链接,在新窗口打开:', url)
Message.info('视频播放失败,检测到网页链接,正在新窗口打开...')
window.open(url, '_blank')
emit('close') // 关闭播放器
return
}
// 处理重连逻辑
handleRetry(url)
})
art.on('video:ended', () => {
console.log('视频播放结束')
// 视频结束时启动自动下一集
if (autoNextEnabled.value && hasNextEpisode()) {
startAutoNextCountdown()
} else if (!hasNextEpisode()) {
Message.info('全部播放完毕')
}
})
art.on('destroy', () => {
console.log('ArtPlayer 已销毁')
// 清理自动下一集相关资源
cancelAutoNext()
})
artPlayerInstance.value = art
} catch (error) {
console.error('创建 ArtPlayer 实例失败:', error)
Message.error('播放器初始化失败')
emit('error', '播放器初始化失败')
}
}
// 关闭播放器
const closePlayer = () => {
console.log('关闭 ArtPlayer 播放器')
// 重置重连状态
resetRetryState()
// 清理播放器实例
if (artPlayerInstance.value) {
// 清理 HLS 实例
if (artPlayerInstance.value.hls) {
artPlayerInstance.value.hls.destroy()
artPlayerInstance.value.hls = null
}
artPlayerInstance.value.destroy()
artPlayerInstance.value = null
}
emit('close')
}
// 处理播放器类型变更
const handlePlayerTypeChange = (newType) => {
emit('player-change', newType)
}
// 打开片头片尾设置弹窗
const openSkipSettingsDialog = () => {
showSkipSettingsDialog.value = true
}
// 保存片头片尾设置
const saveSkipSettings = (settings) => {
saveSkipSettingsComposable(settings)
Message.success('片头片尾设置已保存')
closeSkipSettingsDialog()
}
// 处理重连逻辑
const handleRetry = (url) => {
if (isRetrying.value) {
return // 如果正在重连,避免重复触发
}
if (retryCount.value < maxRetries.value) {
isRetrying.value = true
retryCount.value++
console.log(`ArtPlayer 播放失败,正在进行第 ${retryCount.value} 次重连...`)
Message.warning(`播放失败,正在进行第 ${retryCount.value} 次重连...`)
// 延迟重连,避免频繁重试
setTimeout(() => {
if (artPlayerInstance.value) {
try {
// 重新加载视频
artPlayerInstance.value.switchUrl(url)
isRetrying.value = false
} catch (error) {
console.error('重连时出错:', error)
isRetrying.value = false
handleRetry(url) // 递归重试
}
}
}, 2000 * retryCount.value) // 递增延迟:2秒、4秒、6秒
} else {
// 超过最大重连次数
console.error('ArtPlayer 重连次数已达上限,停止重连')
Message.error(`视频播放失败,已重试 ${maxRetries.value} 次,请检查视频链接或网络连接`)
emit('error', '视频播放失败,重连次数已达上限')
// 重置重连计数器
retryCount.value = 0
isRetrying.value = false
}
}
// 重置重连状态
const resetRetryState = () => {
retryCount.value = 0
isRetrying.value = false
}
// 计算动态高度
const calculateDynamicHeight = () => {
if (!artPlayerContainer.value) return 450
const containerWidth = artPlayerContainer.value.offsetWidth
if (containerWidth === 0) return 450
// 按照 16:9 的比例计算高度
const aspectRatio = 16 / 9
let calculatedHeight = containerWidth / aspectRatio
// 设置最小和最大高度限制
const minHeight = 300
const maxHeight = Math.min(window.innerHeight * 0.7, 600)
calculatedHeight = Math.max(minHeight, Math.min(calculatedHeight, maxHeight))
console.log(`容器宽度: ${containerWidth}px, 计算高度: ${calculatedHeight}px`)
return Math.round(calculatedHeight)
}
// 自动下一集功能相关函数
// 检查是否有下一集
const hasNextEpisode = () => {
return props.episodes.length > 0 && props.currentEpisodeIndex < props.episodes.length - 1
}
// 获取下一集信息
const getNextEpisode = () => {
if (!hasNextEpisode()) return null
return props.episodes[props.currentEpisodeIndex + 1]
}
// 开始自动下一集倒计时
const startAutoNextCountdown = () => {
if (!autoNextEnabled.value || !hasNextEpisode()) return
console.log('开始自动下一集')
// 如果开启了倒计时,显示倒计时弹窗
if (countdownEnabled.value) {
autoNextCountdown.value = 10 // 10秒倒计时
showAutoNextDialog.value = true
autoNextTimer.value = setInterval(() => {
autoNextCountdown.value--
if (autoNextCountdown.value <= 0) {
clearInterval(autoNextTimer.value)
autoNextTimer.value = null
showAutoNextDialog.value = false
playNextEpisode()
}
}, 1000)
} else {
// 直接播放下一集,不显示倒计时
playNextEpisode()
}
}
// 取消自动下一集
const cancelAutoNext = () => {
if (autoNextTimer.value) {
clearInterval(autoNextTimer.value)
autoNextTimer.value = null
}
autoNextCountdown.value = 0
showAutoNextDialog.value = false
console.log('用户取消自动下一集')
}
// 立即播放下一集
const playNextEpisode = () => {
if (!hasNextEpisode()) {
Message.info('已经是最后一集了')
return
}
const nextEpisode = getNextEpisode()
// 清理倒计时
cancelAutoNext()
// 通知父组件切换到下一集
emit('next-episode', props.currentEpisodeIndex + 1)
// 移除重复的播放提示,由父组件VideoDetail统一处理
// Message.success(`开始播放: ${nextEpisode.name}`)
}
// 切换自动下一集开关
const toggleAutoNext = () => {
autoNextEnabled.value = !autoNextEnabled.value
if (!autoNextEnabled.value) {
cancelAutoNext()
}
}
// 切换倒计时开关
const toggleCountdown = () => {
countdownEnabled.value = !countdownEnabled.value
console.log('倒计时开关:', countdownEnabled.value ? '开启' : '关闭')
if (!countdownEnabled.value) {
cancelAutoNext()
}
}
// 滚动到当前选集位置
const scrollToCurrentEpisode = async () => {
// 等待DOM更新
await nextTick()
if (!episodeListRef.value || props.currentEpisodeIndex < 0) {
return
}
// 查找当前选集按钮
const currentButton = episodeListRef.value.querySelector('.episode-item.current')
if (!currentButton) {
return
}
const container = episodeListRef.value
const containerHeight = container.clientHeight
const containerScrollHeight = container.scrollHeight
const buttonTop = currentButton.offsetTop
const buttonHeight = currentButton.offsetHeight
// 计算滚动位置,让当前选集出现在容器的中间偏上位置(约30%处)
const targetPosition = buttonTop + (buttonHeight / 2) - (containerHeight * 0.3)
// 确保滚动位置在有效范围内
const maxScrollTop = containerScrollHeight - containerHeight
const targetScrollTop = Math.max(0, Math.min(targetPosition, maxScrollTop))
// 只有当需要滚动的距离超过一定阈值时才执行滚动
const currentScrollTop = container.scrollTop
const scrollDistance = Math.abs(targetScrollTop - currentScrollTop)
if (scrollDistance > 50) { // 滚动距离超过50px才执行
container.scrollTo({
top: targetScrollTop,
behavior: 'smooth'
})
console.log(`自动滚动到当前选集: 第${props.currentEpisodeIndex + 1}集,滚动距离: ${scrollDistance}px`)
} else {
console.log(`当前选集已在可视区域中心,无需滚动: 第${props.currentEpisodeIndex + 1}集`)
}
}
// 创建选集layer的HTML内容
const createEpisodeLayerHTML = () => {
if (!props.episodes || props.episodes.length === 0) {
return '<div class="episode-layer-background"></div>'
}
const episodeItems = props.episodes.map((episode, index) => {
const isCurrentEpisode = index === props.currentEpisodeIndex
return `
<button
class="episode-layer-item ${isCurrentEpisode ? 'current' : ''}"
data-episode-index="${index}"
>
<span class="episode-layer-number">${index + 1}</span>
<span class="episode-layer-name">${episode.name || `第${index + 1}集`}</span>
</button>
`
}).join('')
return `
<div class="episode-layer-background">
<div class="episode-layer-content">
<div class="episode-layer-header">
<h3>选择集数</h3>
<button class="episode-layer-close">×</button>
</div>
<div class="episode-layer-list">
${episodeItems}
</div>
</div>
</div>
`
}
// 显示选集layer
const showEpisodeLayer = () => {
if (!artPlayerInstance.value) return
try {
// 更新layer内容和样式
artPlayerInstance.value.layers.update({
name: 'episodeLayer',
html: createEpisodeLayerHTML(),
style: {
position: 'absolute',
top: '0',
left: '0',
width: '100%',
height: '100%',
background: 'rgba(0, 0, 0, 0.8)',
display: 'flex',
zIndex: '100',
padding: '0',
boxSizing: 'border-box',
overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center'
}
})
// 添加事件监听器
nextTick(() => {
const episodeLayer = artPlayerInstance.value.layers.episodeLayer
if (episodeLayer) {
// 使用事件委托处理点击事件
episodeLayer.addEventListener('click', handleEpisodeLayerClick)
}
})
console.log('显示选集layer')
} catch (error) {
console.error('显示选集layer失败:', error)
}
}
// 处理选集layer的点击事件
const handleEpisodeLayerClick = (event) => {
const target = event.target.closest('.episode-layer-item')
const closeBtn = event.target.closest('.episode-layer-close')
const background = event.target.closest('.episode-layer-background')
if (closeBtn || (background && event.target === background)) {
// 点击关闭按钮或背景,隐藏layer
hideEpisodeLayer()
} else if (target) {
// 点击选集项