-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathVideoWidget_vlc.py
1161 lines (1068 loc) · 48.1 KB
/
VideoWidget_vlc.py
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
"""
DD监控室最重要的模块之一 视频播放窗口 现已全部从QMediaPlayer迁移至VLC内核播放(klite问题是在太多了。。。)
包含视频缓存播放、音量管理、弹幕窗
遇到不确定的播放状态就调用MediaReload()函数 我已经在里面写好了全部的处理 会自动获取直播间状态并进行对应的刷新操作
"""
import requests
import json
import os
import time
import shutil
import random
from PyQt5.QtWidgets import * # QAction,QFileDialog
from PyQt5.QtGui import * # QIcon,QPixmap
from PyQt5.QtCore import * # QSize
from CommonWidget import Slider
from remote import remoteThread
from danmu import TextBrowser
import vlc
import platform
import logging
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
'Referer': 'https://live.bilibili.com'
}
class PushButton(QPushButton):
"""文字/图标按钮"""
def __init__(self, icon='', text=''):
super(PushButton, self).__init__()
self.setFixedSize(30, 30)
self.setStyleSheet('background-color:#00000000')
if icon:
self.setIcon(icon)
elif text:
self.setText(text)
class GetMediaURL(QThread):
"""获取直播推流并缓存
TODO: 换用 bilibili_api.live.get_room_play_url(room_id)
"""
cacheName = pyqtSignal(str)
copyFile = pyqtSignal(str)
downloadError = pyqtSignal()
def __init__(self, id, cacheFolder, maxCacheSize, saveCachePath):
super(GetMediaURL, self).__init__()
self.id = id
self.cacheFolder = cacheFolder
self.roomID = '0'
self.recordToken = False
self.quality = 250
self.downloadToken = False
self.maxCacheSize = maxCacheSize
self.saveCachePath = saveCachePath
self.checkTimer = QTimer()
self.checkTimer.timeout.connect(self.checkDownlods)
def checkDownlods(self):
if self.downloadToken:
self.downloadToken = False
else:
self.downloadError.emit()
def setConfig(self, roomID, quality):
self.roomID = roomID
self.quality = quality
def getStreamUrl(self):
url = "https://api.live.bilibili.com/xlive/app-room/v2/index/getRoomPlayInfo"
onlyAudio = self.quality < 0
params = {
"appkey": "iVGUTjsxvpLeuDCf",
"build": 6215200,
"c_locale": "zh_CN",
"channel": "bili",
"codec": 0,
"device": "android",
"device_name": "VTR-AL00",
"dolby": 1,
"format": "0,2",
"free_type": 0,
"http": 1,
"mask": 0,
"mobi_app": "android",
"network": "wifi",
"no_playurl": 0,
"only_audio": int(onlyAudio),
"only_video": 0,
"platform": "android",
"play_type": 0,
"protocol": "0,1",
"qn": (onlyAudio and 10000) or (not onlyAudio and self.quality),
"room_id": self.roomID,
"s_locale": "zh_CN",
"statistics": "{\"appId\":1,\"platform\":3,\"version\":\"6.21.5\",\"abtest\":\"\"}",
"ts": int(time.time())
}
r = requests.get(url, params=params)
j = r.json()
baseUrl = j['data']['playurl_info']['playurl']['stream'][0]['format'][0]['codec'][0]['base_url']
extra = j['data']['playurl_info']['playurl']['stream'][0]['format'][0]['codec'][0]['url_info'][0]['extra']
host = j['data']['playurl_info']['playurl']['stream'][0]['format'][0]['codec'][0]['url_info'][0]['host']
# let base_url = jqXHR.responseJSON.data.playurl_info.playurl.stream[0].format[0].codec[0].base_url
# let extra = jqXHR.responseJSON.data.playurl_info.playurl.stream[0].format[0].codec[0].url_info[0].extra
# let host = jqXHR.responseJSON.data.playurl_info.playurl.stream[0].format[0].codec[0].url_info[0].host
# streamURL = host + base_url + extra
streamUrl = host + baseUrl + extra
return streamUrl
def run(self):
# api = r'https://api.live.bilibili.com/room/v1/Room/playUrl?cid=%s&platform=web&qn=%s' % (
# self.roomID, self.quality)
# r = requests.get(api)
try:
# url = json.loads(r.text)['data']['durl'][0]['url']
url = self.getStreamUrl()
fileName = '%s/%s.flv' % (self.cacheFolder, self.id)
download = requests.get(url, stream=True, headers=header)
logging.debug(download.headers)
self.recordToken = True
contentCnt = 0
while True:
try:
self.cacheVideo = open(fileName, 'wb') # 等待上次缓存关闭
break
except:
time.sleep(0.1)
for chunk in download.iter_content(chunk_size=512):
if not self.recordToken:
break
if chunk:
self.downloadToken = True
self.cacheVideo.write(chunk)
contentCnt += 1
if not contentCnt % self.maxCacheSize: # 缓存超过用户设置的缓存大小(默认1GB)清除缓存刷新一次 原画大约要20分钟-30分钟
self.downloadError.emit()
elif contentCnt == 50:
self.cacheName.emit(fileName)
self.cacheVideo.close()
time.sleep(0.1) # 等待0.1秒确保关闭
try:
# 如果备份路径有效
if self.saveCachePath and os.path.exists(self.saveCachePath) and os.path.getsize(fileName):
# 随机命名防止重名
renameFile = '%s/%s.flv' % (self.cacheFolder,
random.randint(50, 10000000))
os.rename(fileName, renameFile)
self.copyFile.emit(renameFile) # 发射信号备份缓存
else:
os.remove(fileName) # 清除缓存
except Exception as e:
logging.error(str(e))
except Exception as e:
logging.error(str(e))
logging.exception('直播地址获取失败 / 缓存视频出错')
class VideoFrame(QFrame):
"""视频播放容器"""
rightClicked = pyqtSignal(QEvent)
leftClicked = pyqtSignal()
doubleClicked = pyqtSignal()
def __init__(self):
super(VideoFrame, self).__init__()
self.setAcceptDrops(True)
def mousePressEvent(self, QMouseEvent):
if QMouseEvent.button() == Qt.RightButton:
self.rightClicked.emit(QMouseEvent)
elif QMouseEvent.button() == Qt.LeftButton:
self.leftClicked.emit()
def mouseDoubleClickEvent(self, QMouseEvent):
self.doubleClicked.emit()
class ExportCache(QThread):
"""导出缓存的视频"""
finish = pyqtSignal(list)
def __init__(self):
super(ExportCache, self).__init__()
self.ori = ''
self.dst = ''
self.cut = False
def setArgs(self, ori, dst):
self.ori, self.dst = ori, dst
def run(self):
try:
if self.cut:
shutil.move(self.ori, self.dst)
self.cut = False
else:
shutil.copy(self.ori, self.dst)
self.finish.emit([True, self.dst]) # 导出成功
except:
logging.exception('导出缓存失败')
self.finish.emit([False, self.dst])
class ExportTip(QWidget):
"""导出提示"""
def __init__(self):
super(ExportTip, self).__init__()
self.resize(600, 100)
# self.setWindowTitle('导出缓存中')
class VideoWidget(QFrame):
"""
视频播放窗口
"""
mutedChanged = pyqtSignal(list) # 按下静音按钮
volumeChanged = pyqtSignal(list) # 音量滑条改变
addMedia = pyqtSignal(list) # 发送新增的直播
deleteMedia = pyqtSignal(int) # 删除选中的直播
exchangeMedia = pyqtSignal(list) # 交换播放窗口
setDanmu = pyqtSignal() # 发射弹幕设置信号
setTranslator = pyqtSignal(list) # 发送同传关闭信号
changeQuality = pyqtSignal(list) # 修改画质
changeAudioChannel = pyqtSignal(list) # 修改音效
popWindow = pyqtSignal(list) # 弹出悬浮窗
hideBarKey = pyqtSignal() # 隐藏控制条快捷键
fullScreenKey = pyqtSignal() # 全屏快捷键
muteExceptKey = pyqtSignal() # 除了这个播放器 其他全部静音快捷键
closePopWindow = pyqtSignal(list) # 关闭悬浮窗
def __init__(self, id, volume, cacheFolder, top=False, title='', resize=[],
textSetting=[True, 20, 2, 6, 0, '【 [ {', 10, 0], maxCacheSize=2048000,
saveCachePath='', startWithDanmu=True, hardwareDecode=True):
super(VideoWidget, self).__init__()
self.setAcceptDrops(True)
self.installEventFilter(self)
self.id = id
self.title = ''
self.uname = ''
self.oldTitle = ''
self.oldUname = ''
self.hoverToken = False
self.roomID = '0' # 初始化直播间房号
self.liveStatus = 0 # 初始化直播状态为0
self.pauseToken = False
self.quality = 250
self.audioChannel = 0 # 0 原始音效 5 杜比音效
self.volume = volume
self.volumeAmplify = 1.0 # 音量加倍
self.muted = False
self.hardwareDecode = hardwareDecode
self.leftButtonPress = False
self.rightButtonPress = False
self.fullScreen = False
self.userPause = False # 用户暂停
self.cacheName = ''
self.maxCacheSize = maxCacheSize
self.saveCachePath = saveCachePath
self.startWithDanmu = startWithDanmu
# 容器设置
self.setFrameShape(QFrame.Box)
self.setObjectName('video')
self.top = top
self.name_str = f"悬浮窗{self.id}"if self.top else f"嵌入窗{self.id}"
if top:
self.setWindowFlags(Qt.Window)
else:
self.setStyleSheet(
'#video{border-width:1px;border-style:solid;border-color:gray}')
self.textSetting = textSetting
self.horiPercent = [0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0][self.textSetting[2]]
self.vertPercent = [0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0][self.textSetting[3]]
self.filters = textSetting[5].split(' ')
self.opacity = 100
if top:
self.setWindowFlag(Qt.WindowStaysOnTopHint)
if title:
if top:
self.setWindowTitle('%s %s' % (title, id + 1 - 9))
else:
self.setWindowTitle('%s %s' % (title, id + 1))
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
# ---- 弹幕机 ----
# 必须赶在resizeEvent和moveEvent之前初始化textbrowser
self.textBrowser = TextBrowser(self)
self.setDanmuOpacity(self.textSetting[1]) # 设置弹幕透明度
self.textBrowser.optionWidget.opacitySlider.setValue(
self.textSetting[1]) # 设置选项页透明条
self.textBrowser.optionWidget.opacitySlider.value.connect(
self.setDanmuOpacity)
self.setHorizontalPercent(self.textSetting[2]) # 设置横向占比
self.textBrowser.optionWidget.horizontalCombobox.setCurrentIndex(
self.textSetting[2]) # 设置选项页占比框
self.textBrowser.optionWidget.horizontalCombobox.currentIndexChanged.connect(
self.setHorizontalPercent)
self.setVerticalPercent(self.textSetting[3]) # 设置横向占比
self.textBrowser.optionWidget.verticalCombobox.setCurrentIndex(
self.textSetting[3]) # 设置选项页占比框
self.textBrowser.optionWidget.verticalCombobox.currentIndexChanged.connect(
self.setVerticalPercent)
self.setTranslateBrowser(self.textSetting[4])
self.textBrowser.optionWidget.translateCombobox.setCurrentIndex(
self.textSetting[4]) # 设置同传窗口
self.textBrowser.optionWidget.translateCombobox.currentIndexChanged.connect(
self.setTranslateBrowser)
self.setTranslateFilter(self.textSetting[5]) # 同传过滤字符
self.textBrowser.optionWidget.translateFitler.setText(
self.textSetting[5])
self.textBrowser.optionWidget.translateFitler.textChanged.connect(
self.setTranslateFilter)
self.setFontSize(self.textSetting[6]) # 设置弹幕字体大小
self.textBrowser.optionWidget.fontSizeCombox.setCurrentIndex(
self.textSetting[6])
self.textBrowser.optionWidget.fontSizeCombox.currentIndexChanged.connect(
self.setFontSize)
self.setMsgsBrowser(self.textSetting[7])
self.textBrowser.optionWidget.showEnterRoom.setCurrentIndex(
self.textSetting[7]) # 设置礼物和进入提示窗口
self.textBrowser.optionWidget.showEnterRoom.currentIndexChanged.connect(
self.setMsgsBrowser)
self.textBrowser.closeSignal.connect(self.closeDanmu)
self.textBrowser.moveSignal.connect(self.moveTextBrowser)
if not self.startWithDanmu: # 如果启动隐藏被设置,隐藏弹幕机
self.textSetting[0] = False
self.textBrowser.hide()
self.textPosDelta = QPoint(0, 0) # 弹幕框和窗口之间的坐标差
self.deltaX = 0
self.deltaY = 0
# ---- 播放器布局设置 ----
# 播放器
self.videoFrame = VideoFrame() # 新版本vlc内核播放器
self.videoFrame.rightClicked.connect(self.rightMouseClicked)
self.videoFrame.leftClicked.connect(self.leftMouseClicked)
self.videoFrame.doubleClicked.connect(self.doubleClick)
layout.addWidget(self.videoFrame, 0, 0, 12, 12)
# vlc 实例
self.instance = vlc.Instance()
self.newPlayer() # 实例化 player
# 直播间标题
self.topLabel = QLabel()
self.topLabel.setFixedHeight(30)
# self.topLabel.setAlignment(Qt.AlignCenter)
self.topLabel.setObjectName('frame')
self.topLabel.setStyleSheet("background-color:#293038")
# self.topLabel.setFixedHeight(32)
self.topLabel.setFont(QFont('微软雅黑', 15, QFont.Bold))
layout.addWidget(self.topLabel, 0, 0, 1, 12)
self.topLabel.hide()
# 控制栏容器
self.frame = QWidget()
self.frame.setObjectName('frame')
self.frame.setStyleSheet("background-color:#293038")
self.frame.setFixedHeight(50)
frameLayout = QHBoxLayout(self.frame)
frameLayout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.frame, 11, 0, 1, 12)
self.frame.hide()
# ---- 嵌入式播放器 控制栏 ----
# 主播名
self.titleLabel = QLabel()
self.titleLabel.setMaximumWidth(150)
self.titleLabel.setStyleSheet('background-color:#00000000')
self.setTitle()
frameLayout.addWidget(self.titleLabel)
# 播放/暂停
self.play = PushButton(self.style().standardIcon(QStyle.SP_MediaPause))
self.play.clicked.connect(self.mediaPlay)
frameLayout.addWidget(self.play)
# 刷新
self.reload = PushButton(
self.style().standardIcon(QStyle.SP_BrowserReload))
self.reload.clicked.connect(self.mediaReload)
frameLayout.addWidget(self.reload)
# 音量开关
self.volumeButton = PushButton(
self.style().standardIcon(QStyle.SP_MediaVolume))
self.volumeButton.clicked.connect(self.mediaMute)
frameLayout.addWidget(self.volumeButton)
# 音量滑条
self.slider = Slider()
self.slider.setStyleSheet('background-color:#00000000')
self.slider.value.connect(self.setVolume)
frameLayout.addWidget(self.slider)
# 弹幕开关
self.danmuButton = PushButton(text='弹')
self.danmuButton.clicked.connect(self.showDanmu)
frameLayout.addWidget(self.danmuButton)
# 关闭窗口
self.stop = PushButton(self.style().standardIcon(
QStyle.SP_DialogCancelButton))
self.stop.clicked.connect(self._mediaStop)
frameLayout.addWidget(self.stop)
# ---- IO 交互设置 ----
# 单开线程获取视频流
self.getMediaURL = GetMediaURL(
self.id, cacheFolder, maxCacheSize, saveCachePath)
self.getMediaURL.cacheName.connect(self.setMedia)
self.getMediaURL.copyFile.connect(self.copyCache)
self.getMediaURL.downloadError.connect(self.mediaReload)
self.danmu = remoteThread(self.roomID)
# 导出配置
self.exportCache = ExportCache()
self.exportCache.finish.connect(self.exportFinish)
self.exportTip = ExportTip()
# ---- 定时器 ----
# 弹幕机位置匹配
self.moveTimer = QTimer()
self.moveTimer.timeout.connect(self.initTextPos)
self.moveTimer.start(50)
# self.reloadDanmuTimer = QTimer()
# self.reloadDanmuTimer.timeout.connect(self.reloadDanmu)
# self.reloadDanmuTimer.start(10000)
# 检查播放卡住的定时器
self.checkPlaying = QTimer()
self.checkPlaying.timeout.connect(self.checkPlayStatus)
# 最后再 resize 避免有变量尚未初始化
if resize:
self.resize(resize[0], resize[1])
logging.info(f"{self.name_str} VLC 播放器构造完毕, 缓存大小: %dkb, 缓存路径: %s, 置顶?: %s, 启用弹幕?: %s" %
(self.maxCacheSize, self.saveCachePath, self.top, self.startWithDanmu))
self.audioTimer = QTimer()
self.audioTimer.timeout.connect(self.checkAudio)
self.audioTimer.setInterval(100)
def checkPlayStatus(self): # 播放卡住了
if not self.player.is_playing() and not self.isHidden() and self.liveStatus != 0 and not self.userPause:
self.retryTimes += 1
if self.retryTimes > 10: # 10秒内未刷新
self.mediaReload() # 彻底刷新
else:
# self.player.pause() # 不完全刷新
self.player.stop()
self.player.release()
self.player = self.instance.media_player_new()
self.player.video_set_mouse_input(False)
self.player.video_set_key_input(False)
if platform.system() == 'Windows':
self.player.set_hwnd(self.videoFrame.winId())
elif platform.system() == 'Darwin': # for MacOS
self.player.set_nsobject(int(self.videoFrame.winId()))
else:
self.player.set_xwindow(self.videoFrame.winId())
if self.hardwareDecode:
self.media = self.instance.media_new(
self.cacheName, 'avcodec-hw=dxva2') # 设置vlc并硬解播放
else:
self.media = self.instance.media_new(self.cacheName) # 软解
self.player.set_media(self.media) # 设置视频
self.player.audio_set_channel(self.audioChannel)
self.player.play()
self.audioTimer.stop()
self.audioTimer.start() # 检测音量
def checkAudio(self):
volume = int(self.volume * self.volumeAmplify)
if self.player.audio_get_volume() != volume:
self.player.audio_set_volume(volume)
elif self.player.audio_get_mute != self.muted:
self.player.audio_set_mute(self.muted)
else:
self.audioTimer.stop()
def initTextPos(self): # 初始化弹幕机位置
videoPos = self.mapToGlobal(self.videoFrame.pos())
if self.textBrowser.pos() != videoPos:
self.textBrowser.move(videoPos)
else:
self.moveTimer.stop()
def setDanmuOpacity(self, value):
if value < 7:
value = 7 # 最小透明度
self.textSetting[1] = value # 记录设置
value = int(value / 101 * 256)
color = str(hex(value))[2:] + '000000'
self.textBrowser.textBrowser.setStyleSheet(
'background-color:#%s' % color)
self.textBrowser.transBrowser.setStyleSheet(
'background-color:#%s' % color)
self.textBrowser.msgsBrowser.setStyleSheet(
'background-color:#%s' % color)
self.setDanmu.emit()
def setHorizontalPercent(self, index): # 设置弹幕框水平宽度
self.textSetting[2] = index
self.horiPercent = [0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0][index] # 记录横向占比
width = self.width() * self.horiPercent
self.textBrowser.resize(width, self.textBrowser.height())
# if width > 240:
# self.textBrowser.textBrowser.setFont(QFont('Microsoft JhengHei', 17, QFont.Bold))
# self.textBrowser.transBrowser.setFont(QFont('Microsoft JhengHei', 17, QFont.Bold))
# elif 100 < width <= 240:
# self.textBrowser.textBrowser.setFont(QFont('Microsoft JhengHei', width // 20 + 5, QFont.Bold))
# self.textBrowser.transBrowser.setFont(QFont('Microsoft JhengHei', width // 20 + 5, QFont.Bold))
# else:
# self.textBrowser.textBrowser.setFont(QFont('Microsoft JhengHei', 10, QFont.Bold))
# self.textBrowser.transBrowser.setFont(QFont('Microsoft JhengHei', 10, QFont.Bold))
self.textBrowser.textBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.transBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.msgsBrowser.verticalScrollBar().setValue(100000000)
self.setDanmu.emit()
def setVerticalPercent(self, index): # 设置弹幕框垂直高度
self.textSetting[3] = index
self.vertPercent = [0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0][index] # 记录纵向占比
self.textBrowser.resize(self.textBrowser.width(),
self.height() * self.vertPercent)
self.textBrowser.textBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.transBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.msgsBrowser.verticalScrollBar().setValue(100000000)
self.setDanmu.emit()
def setTranslateBrowser(self, index):
self.textSetting[4] = index
if index == 0: # 显示弹幕和同传
self.textBrowser.textBrowser.show()
self.textBrowser.transBrowser.show()
elif index == 1: # 只显示弹幕
self.textBrowser.transBrowser.hide()
self.textBrowser.textBrowser.show()
elif index == 2: # 只显示同传
self.textBrowser.textBrowser.hide()
self.textBrowser.transBrowser.show()
self.textBrowser.resize(
self.width() * self.horiPercent, self.height() * self.vertPercent)
self.setDanmu.emit()
def setMsgsBrowser(self, index):
self.textSetting[7] = index
if index < 3: # 显示弹幕和同传
self.textBrowser.msgsBrowser.show()
elif index == 3: # 只显示弹幕
self.textBrowser.msgsBrowser.hide()
self.textBrowser.resize(
self.width() * self.horiPercent, self.height() * self.vertPercent)
self.setDanmu.emit()
def setTranslateFilter(self, filterWords):
self.textSetting[5] = filterWords
self.filters = filterWords.split(' ')
self.setDanmu.emit()
def setFontSize(self, index):
self.textSetting[6] = index
self.textBrowser.textBrowser.setFont(
QFont('Microsoft JhengHei', index + 5, QFont.Bold))
self.textBrowser.transBrowser.setFont(
QFont('Microsoft JhengHei', index + 5, QFont.Bold))
self.textBrowser.msgsBrowser.setFont(
QFont('Microsoft JhengHei', index + 5, QFont.Bold))
self.setDanmu.emit()
def resizeEvent(self, QEvent):
self.titleLabel.hide() if self.width() < 350 else self.titleLabel.show()
self.play.hide() if self.width() < 300 else self.play.show()
self.danmuButton.hide() if self.width() < 250 else self.danmuButton.show()
self.slider.hide() if self.width() < 200 else self.slider.show()
width = self.width() * self.horiPercent
self.textBrowser.resize(width, self.height() * self.vertPercent)
self.textBrowser.textBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.transBrowser.verticalScrollBar().setValue(100000000)
self.textBrowser.msgsBrowser.verticalScrollBar().setValue(100000000)
self.moveTextBrowser()
def moveEvent(self, QMoveEvent): # 理论上给悬浮窗同步弹幕机用的moveEvent 但不生效 但是又不能删掉 不然交换窗口弹幕机有bug
# videoFrame的坐标要转成globalPos
videoPos = self.mapToGlobal(self.videoFrame.pos())
self.textBrowser.move(videoPos + self.textPosDelta)
def moveTextBrowser(self, point=None):
# videoFrame的坐标要转成globalPos
videoPos = self.mapToGlobal(self.videoFrame.pos())
if point:
danmuX, danmuY = point.x(), point.y()
else:
# textBrowser坐标本身就是globalPos
danmuX, danmuY = self.textBrowser.x(), self.textBrowser.y()
videoX, videoY = videoPos.x(), videoPos.y()
videoW, videoH = self.videoFrame.width(), self.videoFrame.height()
danmuW, danmuH = self.textBrowser.width(), self.textBrowser.height()
smaller = False # 弹幕机尺寸大于播放窗
if danmuW > videoW or danmuH > videoH + 5: # +5是为了在100%纵向的时候可以左右拖 有的屏幕计算会略微超过一两个像素
danmuX, danmuY = videoX, videoY
smaller = True
if not smaller:
if danmuX < videoX:
danmuX = videoX
elif danmuX > videoX + videoW - danmuW:
danmuX = videoX + videoW - danmuW
if danmuY < videoY:
danmuY = videoY
elif danmuY > videoY + videoH - danmuH:
danmuY = videoY + videoH - danmuH
self.textBrowser.move(danmuX, danmuY)
self.textPosDelta = self.textBrowser.pos() - videoPos
self.deltaX, self.deltaY = self.textPosDelta.x(
) / self.width(), self.textPosDelta.y() / self.height()
def enterEvent(self, QEvent):
self.hoverToken = True
self.topLabel.show()
self.frame.show()
def leaveEvent(self, QEvent):
self.hoverToken = False
self.topLabel.hide()
self.frame.hide()
def doubleClick(self):
if not self.top: # 非弹出类悬浮窗
self.popWindow.emit(
[self.id, self.roomID, self.quality, True, self.startWithDanmu])
self.mediaStop() # 直接停止播放原窗口
def leftMouseClicked(self): # 设置drag事件 发送拖动封面的房间号
drag = QDrag(self)
mimeData = QMimeData()
if self.top: # 悬浮窗
# mimeData.setText('roomID:%s' % self.roomID)
mimeData.setText('')
else:
mimeData.setText('exchange:%s:%s' % (self.id, self.roomID))
drag.setMimeData(mimeData)
drag.exec_()
logging.debug(f'{self.name_str} drag exchange:%s:%s' %
(self.id, self.roomID))
def dragEnterEvent(self, QDragEnterEvent):
QDragEnterEvent.accept()
def dropEvent(self, QDropEvent):
if QDropEvent.mimeData().hasText:
text = QDropEvent.mimeData().text() # 拖拽事件
print(text)
if 'roomID' in text: # 从cover拖拽新直播间
self.stopDanmuMessage()
self.roomID = text.split(':')[1]
self.addMedia.emit([self.id, self.roomID])
self.mediaReload()
self.textBrowser.textBrowser.clear()
self.textBrowser.transBrowser.clear()
self.textBrowser.msgsBrowser.clear()
elif 'exchange' in text: # 交换窗口
fromID, fromRoomID = text.split(':')[1:] # exchange:id:roomID
fromID = int(fromID)
print(fromID, self.id)
if fromID != self.id:
self.exchangeMedia.emit(
[fromID, fromRoomID, self.id, self.roomID])
def rightMouseClicked(self, event):
menu = QMenu()
exportCache = menu.addAction('导出视频缓存')
openBrowser = menu.addAction('打开直播间')
chooseQuality = menu.addMenu('选择画质 ►')
originQuality = chooseQuality.addAction('原画')
if self.quality == 10000:
originQuality.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
bluerayQuality = chooseQuality.addAction('蓝光')
if self.quality == 400:
bluerayQuality.setIcon(
self.style().standardIcon(QStyle.SP_DialogApplyButton))
highQuality = chooseQuality.addAction('超清')
if self.quality == 250:
highQuality.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
lowQuality = chooseQuality.addAction('流畅')
if self.quality == 80:
lowQuality.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
onlyAudio = chooseQuality.addAction('仅播声音')
if self.quality == -1:
onlyAudio.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAudioChannel = menu.addMenu('选择音效 ►')
chooseAudioOrigin = chooseAudioChannel.addAction('原始音效')
if self.audioChannel == 0:
chooseAudioOrigin.setIcon(
self.style().standardIcon(QStyle.SP_DialogApplyButton))
chooseAudioDolbys = chooseAudioChannel.addAction('杜比音效')
if self.audioChannel == 5:
chooseAudioDolbys.setIcon(
self.style().standardIcon(QStyle.SP_DialogApplyButton))
chooseAmplify = menu.addMenu('音量增大 ►')
chooseAmp_0_5 = chooseAmplify.addAction('x 0.5')
if self.volumeAmplify == 0.5:
chooseAmp_0_5.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAmp_1 = chooseAmplify.addAction('x 1.0')
if self.volumeAmplify == 1.0:
chooseAmp_1.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAmp_1_5 = chooseAmplify.addAction('x 1.5')
if self.volumeAmplify == 1.5:
chooseAmp_1_5.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAmp_2 = chooseAmplify.addAction('x 2.0')
if self.volumeAmplify == 2.0:
chooseAmp_2.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAmp_3 = chooseAmplify.addAction('x 3.0')
if self.volumeAmplify == 3.0:
chooseAmp_3.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
chooseAmp_4 = chooseAmplify.addAction('x 4.0')
if self.volumeAmplify == 4.0:
chooseAmp_4.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
if not self.top: # 非弹出类悬浮窗
popWindow = menu.addAction('悬浮窗播放')
else: # 弹出的悬浮窗
opacityMenu = menu.addMenu('调节透明度 ►')
percent100 = opacityMenu.addAction('100%')
if self.opacity == 100:
percent100.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
percent80 = opacityMenu.addAction('80%')
if self.opacity == 80:
percent80.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
percent60 = opacityMenu.addAction('60%')
if self.opacity == 60:
percent60.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
percent40 = opacityMenu.addAction('40%')
if self.opacity == 40:
percent40.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
percent20 = opacityMenu.addAction('20%')
if self.opacity == 20:
percent20.setIcon(self.style().standardIcon(
QStyle.SP_DialogApplyButton))
fullScreen = menu.addAction(
'退出全屏') if self.isFullScreen() else menu.addAction('全屏')
exit = menu.addAction('退出')
action = menu.exec_(self.mapToGlobal(event.pos()))
if action == exportCache:
if self.cacheName and os.path.exists(self.cacheName):
saveName = '%s_%s' % (self.uname, self.title)
savePath = QFileDialog.getSaveFileName(
self, "选择保存路径", saveName, "*.flv")[0]
if savePath: # 保存路径有效
self.exportCache.setArgs(self.cacheName, savePath)
self.exportCache.start()
self.exportTip.setWindowTitle('导出缓存至%s' % savePath)
self.exportTip.show()
else:
QMessageBox.information(
self, '导出失败', '未检测到有效缓存\n%s' % self.cacheName, QMessageBox.Ok)
elif action == openBrowser:
if self.roomID != '0':
QDesktopServices.openUrl(
QUrl(r'https://live.bilibili.com/%s' % self.roomID))
elif action == originQuality:
self.changeQuality.emit([self.id, 10000])
self.quality = 10000
self.mediaReload()
elif action == bluerayQuality:
self.changeQuality.emit([self.id, 400])
self.quality = 400
self.mediaReload()
elif action == highQuality:
self.changeQuality.emit([self.id, 250])
self.quality = 250
self.mediaReload()
elif action == lowQuality:
self.changeQuality.emit([self.id, 80])
self.quality = 80
self.mediaReload()
elif action == onlyAudio:
self.changeQuality.emit([self.id, -1])
self.quality = -1
self.mediaReload()
elif action == chooseAudioOrigin:
self.changeAudioChannel.emit([self.id, 0])
self.player.audio_set_channel(0)
self.audioChannel = 0
elif action == chooseAudioDolbys:
self.changeAudioChannel.emit([self.id, 5])
self.player.audio_set_channel(5)
self.audioChannel = 5
elif action == chooseAmp_0_5:
self.volumeAmplify = 0.5
self.audioTimer.start()
elif action == chooseAmp_1:
self.volumeAmplify = 1.0
self.audioTimer.start()
elif action == chooseAmp_1_5:
self.volumeAmplify = 1.5
self.audioTimer.start()
elif action == chooseAmp_2:
self.volumeAmplify = 2.0
self.audioTimer.start()
elif action == chooseAmp_3:
self.volumeAmplify = 3.0
self.audioTimer.start()
elif action == chooseAmp_4:
self.volumeAmplify = 4.0
self.audioTimer.start()
if not self.top:
if action == popWindow:
self.popWindow.emit(
[self.id, self.roomID, self.quality, False, self.startWithDanmu])
self.mediaStop() # 停止播放
# self.mediaPlay(1, True) # 暂停播放
elif self.top:
if action == percent100:
self.setWindowOpacity(1)
self.opacity = 100
elif action == percent80:
self.setWindowOpacity(0.8)
self.opacity = 80
elif action == percent60:
self.setWindowOpacity(0.6)
self.opacity = 60
elif action == percent40:
self.setWindowOpacity(0.4)
self.opacity = 40
elif action == percent20:
self.setWindowOpacity(0.2)
self.opacity = 20
elif action == fullScreen:
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
elif action == exit:
if self.top:
self.closePopWindow.emit([self.id, self.roomID])
self.hide()
self.mediaStop()
self.textBrowser.hide()
def closeEvent(self, event):
"""拦截关闭按钮事件,隐藏弹出的悬浮窗
修改务必同步右键菜单的退出事件:"action == exit"
"""
event.ignore() # 忽略关闭事件
if self.top:
self.closePopWindow.emit([self.id, self.roomID])
self.hide()
self.mediaStop()
self.textBrowser.hide()
logging.debug(f"{self.name_str}隐藏")
def exportFinish(self, result):
self.exportTip.hide()
if result[0]:
QMessageBox.information(self, '导出完成', result[1], QMessageBox.Ok)
else:
QMessageBox.information(self, '导出失败', result[1], QMessageBox.Ok)
def setVolume(self, value):
self.player.audio_set_volume(int(value * self.volumeAmplify))
self.volume = value # 记录volume值 每次刷新要用到
self.slider.setValue(value)
self.volumeChanged.emit([self.id, value])
def closeDanmu(self):
self.textSetting[0] = False
# self.setDanmu.emit([self.id, False]) # 旧版信号 已弃用
# def closeTranslator(self):
# self.setTranslator.emit([self.id, False])
def stopDanmuMessage(self):
self.stopDanmu()
def showDanmu(self):
if self.textBrowser.isHidden():
self.textBrowser.show()
if not self.startWithDanmu:
self.danmu.message.connect(self.playDanmu)
self.danmu.terminate()
self.danmu.start()
self.textSetting[0] = True
self.startWithDanmu = True
else:
self.textBrowser.hide()
self.startWithDanmu = False
self.textSetting[0] = not self.textBrowser.isHidden()
self.setDanmu.emit()
def mediaPlay(self, force=0, stopDownload=False, setUserPause=False):
if force == 1:
self.player.set_pause(1)
if setUserPause:
self.userPause = True
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
elif force == 2:
self.player.play()
if setUserPause:
self.userPause = False
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
elif self.player.get_state() == vlc.State.Playing:
self.player.set_pause(1)
self.userPause = True
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
else:
self.player.play()
self.userPause = False
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
if stopDownload:
self.getMediaURL.recordToken = False # 设置停止缓存标志位
self.getMediaURL.checkTimer.stop()
self.checkPlaying.stop()
logging.debug(f"{self.name_str}按下暂停/播放键")
def mediaMute(self, force=0, emit=True):
logging.debug(f"{self.name_str}按下音量开关键")
logging.debug(f" force={force}, emit={emit}")
voice_str = "音量Off" if self.player.audio_get_mute() else "音量On"
logging.debug(f" bgein mute status={voice_str}")
if force == 1:
self.muted = False
# self.player.audio_set_mute(False)
self.volumeButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaVolume))
elif force == 2:
self.muted = True
# self.player.audio_set_mute(True)
self.volumeButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaVolumeMuted))
elif self.player.audio_get_mute():
self.muted = False
# self.player.audio_set_mute(False)
self.volumeButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaVolume))
else:
self.muted = True
# self.player.audio_set_mute(True)
self.volumeButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaVolumeMuted))
self.audioTimer.start()
if emit:
self.mutedChanged.emit([self.id, self.muted])
voice_str = "音量Off" if self.player.audio_get_mute() else "音量On"
logging.debug(f" final mute status={voice_str}")
def mediaReload(self):
self.getMediaURL.recordToken = False # 设置停止缓存标志位
self.getMediaURL.checkTimer.stop()
self.checkPlaying.stop()
if self.roomID != '0':
self.playerRestart()
self.setTitle() # 同时获取最新直播状态
if self.liveStatus == 1: # 直播中
self.getMediaURL.setConfig(
self.roomID, self.quality) # 设置房号和画质
self.getMediaURL.start() # 开始缓存视频
self.getMediaURL.checkTimer.start(3000) # 启动监测定时器
else:
self.mediaStop()
def _mediaStop(self):
self.mediaStop()
def mediaStop(self, deleteMedia=True):
# self.userPause = True
self.oldTitle, self.oldUname = '', ''
self.roomID = '0'
self.topLabel.setText((' 窗口%s 未定义的直播间' %
(self.id + 1))[:20]) # 限制下直播间标题字数
self.titleLabel.setText('未定义')
self.playerRestart()
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))