WebRtcApe.js
47.0 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
//*
// WebRtc
// */
require('../assets/css/mcuStyle.css');
import Emiter from 'Emiter';
import Loger from "Loger";
import $ from "jquery";
import GlobalConfig from 'GlobalConfig';
import ApeConsts from './ApeConsts';
import EngineUtils from 'EngineUtils';
import MessageTypes from 'MessageTypes';
var AgoraRTC = require('../AgoraRTCSDK-2.0.0');
let loger = Loger.getLoger('WebRtcApe');
const SIZE_480 = 480;
const SIZE_360 = 360;
const SIZE_320 = 320;
const SIZE_240 = 240;
const SIZE_160 = 160;
const SIZE_120 = 120;
class WebRtcApe extends Emiter {
constructor() {
super();
this.nameDisplay = "block";//默认显示名字
this.appId = '';
this.appCertificate = "";
this.appRecordingKey = "";
this.setConfigTimestamp = 0;//设置旁路地址的时间戳
this.configPublisherUrl = "";//旁路地址;
this.m3u8Url = "";//旁路拉流地址
this.rtmpUrl = "";//旁路拉流地址
this.channelKey = null;
this.channelId = "";
this.uid = 0;
this.info = ""
this.reAddRemoteStreamDelay = 0;//重连远程视频的计时器
this.rePublishDelay = 0;//重新推流的间隔
this.mode = "interop";
this.client = null;
this.localStream = null;
this.cameras = [];
this.microphones = [];
this.curCameraId = "";
this.curMicrophoneId = "";
this.speakerList = [];//记录讲话的记录
this.remoteVideoList = {};//记录远程视频流
this.pWidth = SIZE_480;
this.pHeight = SIZE_360;
this.pFrameRate = 30;
this.pBitrate = 500;
//120P 0 160x120 15 65
//240P 20 320x240 15 200
//360P_8 37 480x360 30 490
this.videoResolution = "240P";
this.isOpenVideo = true;//是否开启摄像头,默认为开启,如果获取不到麦克风的时候会设置为false
this.firstPublishSuccess = false;//记录加入频道成功之后是否推流成功过,离开频道之后需要设置为false
this.isWebSocketDisconnect = false;//记录中途是否已经断开
this.isPublish = false;//当前是否正在推流
this.videoScale = 1;//视图的缩放比例,默认为1;
this.isEnableVideo = true;
this.isEnableAudio = true;
this.normalRemoteViewId = "";
this.normalRemoteStyle = "";
this.normalRemoteVideoWidth = SIZE_480;
this.normalRemoteVideoHeight = SIZE_360;
this.localViewId = "";
this.localStyle = "";
this.localVideoWidth = SIZE_480;
this.localVideoHeight = SIZE_360;
this.hostRemoteViewId = "";
this.hostRemoteStyle = "";
this.hostRemoteVideoWidth = SIZE_480;
this.hostRemoteVideoHeight = SIZE_360;
this.invisibleViewId = "";
this.invisibleStyle = "";
this.invisibleVideoWidth = SIZE_480;
this.invisibleVideoHeight = SIZE_360;
this.xdyRemote = "xdy_remote";
this.audioMutedIdName = "audioMutedIdName_";
this.videoMutedIdName = "videoMutedIdName_";
this.closeCameraTitle = "close Camera";
this.openCameraTitle = "open Camera";
this.closeMicrophoneTitle = "close Microphone";
this.openMicrophoneTitle = "open Microphone";
this.localWebRtcVideoClass = 'localWebRtcVideoClass';//本地视图统一的class名称
this.invisibleWebRtcVideoClass = 'invisibleWebRtcVideoClass';
this.normalWebRtcVideoClass = 'normalWebRtcVideoClass';
this.hostWebRtcVideoClass = 'hostWebRtcVideoClass';
//webRtc sdk
this.client = AgoraRTC.createClient({mode: this.mode});
this.getDevices(null, (devices)=> {
if (this.cameras && this.cameras.length > 0) {
this.curCameraId = this.cameras[0].deviceId || "";
GlobalConfig.curCamera = this.cameras[0].label || "";
}
if (this.microphones && this.microphones.length > 0) {
this.curMicrophoneId = this.microphones[0].deviceId || "";
GlobalConfig.curMicrophone = this.microphones[0].label || "";
}
});
}
initApp(_params, _callback) {
loger.log("初始化WebRtc");
if (_params) {
this.appId = _params.appId;
}
if (this.client) {
this.client.init(this.appId, () => {
loger.log("初始化WebRtc->成功");
if (_callback) {
_callback({isSuccess: true});
}
}, (err)=> {
loger.error("初始化WebRtc->失败", err);
if (_callback) {
_callback({isSuccess: false, error: err});
}
});
this.addEvent();
}
}
addEvent() {
loger.log("监听webRtc消息");
if (!this.client) {
loger.log("addEvent error:client is null");
return;
}
this.channelKey = "";
this.client.on('error', (err) => {
loger.log("WebRtc异常:", err);
switch (err.reason) {
case "DYNAMIC_KEY_TIMEOUT":
this.client.renewChannelKey(this.channelKey, ()=> {
loger.log("Renew channel key successfully");
}, (err)=> {
loger.log("Renew channel key failed: ", err);
});
break;
case "SOCKET_DISCONNECTED":
//连接断开
this.isWebSocketDisconnect = true;
this._emit(MessageTypes.WEB_RTC_LEAVE_CHANNEL);
break;
case "SOCKET_ERROR":
//连接断开
this.isWebSocketDisconnect = true;
this._emit(MessageTypes.WEB_RTC_LEAVE_CHANNEL);
break;
default :
break;
}
});
this.client.on('stream-published', (evt)=> {
this.reJoinChannelSuccess();
loger.log("webRtc->推流成功->", new Date().getTime());
this.isPublish = true;
this.firstPublishSuccess = true;
GlobalConfig.openCamera = EngineUtils.creatTimestamp();
GlobalConfig.openMicrophones = GlobalConfig.openCamera;
this.isEnableVideo = true;
this.isEnableAudio = true;
GlobalConfig.videoEnabled = true;
GlobalConfig.audioEnabled = true;
this._emit(MessageTypes.USER_DEVICE_STATUS_CHAANGE, {
nodeId: GlobalConfig.nodeId,
userRole: GlobalConfig.userRole,
userName: GlobalConfig.userName,
userId: GlobalConfig.userId,
openCamera: GlobalConfig.openCamera,
openMicrophones: GlobalConfig.openMicrophones
});
this.changePublishStatusAndServerRecord(WebRtcApe.RECORD_STATUS_1);
});
this.client.on('stream-added', (evt)=> {
let stream = evt.stream;
this.reAddRemoteStream(stream);
});
this.client.on('stream-subscribed', (evt)=> {
let stream = evt.stream;
this.addRemoetStreamView(stream);
});
this.client.on('stream-removed', (evt)=> {
let stream = evt.stream;
if (stream) {
stream.stop();
$('#' + this.xdyRemote + stream.getId()).remove();
loger.log("远程视频流已经断开:" + stream.getId());
}
});
this.client.on('peer-leave', (evt)=> {
let stream = evt.stream;
if (stream) {
stream.stop();
$('#' + this.xdyRemote + stream.getId()).remove();
loger.log(evt.uid + " ->离开视频通话频道");
}
});
this.client.on("active-speaker", (evt)=> {
let uid = evt.uid;
let user = GlobalConfig.getUserInfoFromeNodeId(parseInt(uid));
//console.log("active-speaker",user);
/* if (user) {
let roleRole = GlobalConfig.getUserRoleToString(user.role);
this.speakerList.push("当前正在讲话的 [" + roleRole + "] name:" + user.name + " uid:" + uid);
} else {
this.speakerList.push("当前正在讲话的uid:" + uid);
}*/
/* //记录正在讲话的数据,大于50条上报一次
if(this.speakerList.length>20){
loger.log(this.speakerList);
this.speakerList=[];
}*/
});
}
addRemoetStreamView(stream) {
if (stream) {
let uid = stream.getId();
let user = GlobalConfig.getUserInfoFromeNodeId(uid);
let userName = "";
let userRole = ""
if (user) {
userName = user.name || "unknow";
userRole = user.userRole;
}
//添加之前先删除之前存在的重复视图 (查找子元素)
let len = $("#" + this.xdyRemote + uid + " #player_" + uid).length;
if (len < 1) {
loger.log("添加之前先删除之前存在的重复视图", uid);
$("#" + this.xdyRemote + uid).remove();
}
let audioMutedDiv = "";
let videoMutedDiv = "";
let videoAndAudioBox = ""
if (GlobalConfig.isTeachOrAssistant || GlobalConfig.isInvisible) {
if (user && user.videoEnabled == true) {
videoMutedDiv = `<div class="audioAndVideMuted cameraOn" id=${this.videoMutedIdName + uid} title="${this.closeCameraTitle}"></div>`
} else {
videoMutedDiv = `<div class="audioAndVideMuted cameraOff" id=${this.videoMutedIdName + uid} title="${this.closeCameraTitle}"></div>`
}
if (user && user.audioEnabled == true) {
audioMutedDiv = `<div class="audioAndVideMuted microphoneOn " id=${this.audioMutedIdName + uid} title="${this.closeMicrophoneTitle}"></div>`;
} else {
audioMutedDiv = `<div class="audioAndVideMuted microphoneOff " id=${this.audioMutedIdName + uid} title="${this.closeMicrophoneTitle}"></div>`;
}
videoAndAudioBox = `<div class="audioAndVideBox unOpenVideo">${videoMutedDiv + audioMutedDiv}</div>`;
}
if (userRole == ApeConsts.invisible) {
let nameDiv = `<div style="${this.invisibleVideoWidth}px;height:22px; position: absolute;bottom: 2px; right:4px; z-index: 2;overflow:hidden;font-size: 14px;text-align: right; vertical-align: middle;color: #e7e7e7display:${this.nameDisplay}">${userName}</div>`;
//把远程视频添加到监课列表
loger.log("获取远程视频流成功->监课:" + userName + "->" + uid, new Date().getTime());
let viewDiv = `<div id="${this.xdyRemote + uid}" class="${this.invisibleWebRtcVideoClass}" style="width:${this.invisibleVideoWidth * this.videoScale}px;height:${this.invisibleVideoHeight * this.videoScale}px;float: left;margin-right: 1px;">${nameDiv + videoAndAudioBox}</div>`;
$(this.invisibleViewId).append(viewDiv);
} else if (userRole == ApeConsts.host || userRole == ApeConsts.assistant || userRole == ApeConsts.presenter) {
let nameDiv = `<div style="width:${this.hostRemoteVideoWidth}px;height:22px; position: absolute;bottom: 2px;right:4px; z-index: 2;overflow:hidden;font-size: 14px;text-align: right;vertical-align: middle;color: #e7e7e7;display:${this.nameDisplay}">${userName }</div>`;
//把远程视图添加到老师列表
loger.log("获取远程视频流成功->userRole:" + userRole + ":" + userName + "->" + uid, new Date().getTime());
let viewDiv = `<div id="${this.xdyRemote + uid}" class="${this.hostWebRtcVideoClass}" style="width:${this.hostRemoteVideoWidth * this.videoScale}px;height:${this.hostRemoteVideoHeight * this.videoScale}px;float: left;margin-right: 1px;">${nameDiv + videoAndAudioBox}</div>`;
$(this.hostRemoteViewId).prepend(viewDiv);
} else {
let nameDiv = `<div style="width:${this.normalRemoteVideoWidth}px;height:22px; position: absolute;bottom: 2px;right:4px; z-index: 2;overflow:hidden;font-size: 14px;text-align: right;vertical-align: middle;color: #e7e7e7;display:${this.nameDisplay}">${userName}</div>`;
//把视图添加到学生列表
loger.log("获取远程视频流成功->学生:" + userName + "->" + uid, new Date().getTime());
let viewDiv = `<div id="${this.xdyRemote + uid}" class="${this.normalWebRtcVideoClass}" style="width:${this.normalRemoteVideoWidth * this.videoScale}px;height:${this.normalRemoteVideoHeight * this.videoScale}px;float: left;margin-right: 1px;">${nameDiv + videoAndAudioBox}</div>`;
$(this.normalRemoteViewId).append(viewDiv);
}
let audioPlayIcoBox = `<div class="audioPlayIcoBox " id=${"audioPlayIcoBox" + uid} ></div>`;
$("#" + this.xdyRemote + uid).append(audioPlayIcoBox);
$("#" + this.videoMutedIdName + uid).off("click", this._clickVideoMuted.bind(this));
$("#" + this.audioMutedIdName + uid).off("click", this._clickAudioMuted.bind(this));
$("#" + this.videoMutedIdName + uid).on("click", this._clickVideoMuted.bind(this));
$("#" + this.audioMutedIdName + uid).on("click", this._clickAudioMuted.bind(this));
//播放视频,隐藏控制条
try {
$("#bar_" + stream.getId()).hide();
stream.play(this.xdyRemote + stream.getId());
} catch (err) {
//添加之前先删除之前存在的重复视图
let len = $("#" + this.xdyRemote + uid + " #player_" + uid).length;
if (len < 1) {
loger.log("流播放失败->删除视图", uid);
$("#" + this.xdyRemote + uid).remove();
}
}
//设置视图画面不可点
$("#player_" + uid).css("pointer-events", "none");
//更新音视频禁用状态显示
if (uid != GlobalConfig.nodeId) {
this.receiveWebRtcMeiaEnabledChange({
nodeId: uid,
video: Boolean(user.videoEnabled),
audio: Boolean(user.audioEnabled)
});
}
if (user && (user.deviceType == GlobalConfig.deviceIOS || user.deviceType == GlobalConfig.deviceAndroid)) {
this.remoteVideoList[user.nodeId] = stream;
}
}
this.clearInvalidVideoView();
this.reJoinChannelSuccess();
}
/*
*
* 断线后重连成功
* */
reJoinChannelSuccess() {
if (this.isWebSocketDisconnect) {
loger.log("断线重连成功");
this._emit(MessageTypes.WEB_RTC_REJOIN_SUCCESS);
}
this.isWebSocketDisconnect = false;
}
//清除无效的视图
clearInvalidVideoView() {
let normalList = document.getElementsByClassName(this.normalWebRtcVideoClass);
let hostList = document.getElementsByClassName(this.hostWebRtcVideoClass);
let localList = document.getElementsByClassName(this.localWebRtcVideoClass);
let divItem = null;
if (normalList) {
for (let i = normalList.length - 1; i >= 0; i--) {
divItem = normalList[i];
if (divItem && divItem.children.length < 2) {
console.log("删除无效的学生视图");
divItem.remove();
}
}
}
divItem = null;
if (hostList) {
for (let i = hostList.length - 1; i >= 0; i--) {
divItem = hostList[i];
if (divItem && divItem.children.length < 2) {
console.log("删除无效的老师视图");
divItem.remove();
}
}
}
divItem = null;
if (localList) {
for (let i = localList.length - 1; i >= 0; i--) {
divItem = localList[i];
if (divItem && divItem.children.length < 2) {
console.log("删除无效的本地视图");
divItem.remove();
}
}
}
divItem = null;
}
//重新添加远程视频
reAddRemoteStream(_stream) {
if (!_stream) {
return;
}
let user = GlobalConfig.getUserRoleFromeNodeId(_stream.getId());
if (user.openCamera <= 0) {
loger.log("远程流已经停止,不需要再连接: " + _stream.getId(), new Date().getTime());
return;
}
loger.log("添加一个远程视频流: " + _stream.getId(), new Date().getTime());
this.client.subscribe(_stream, (err)=> {
//clearTimeout(this.reAddRemoteStreamDelay);
if (err == "INVALID_REMOTE_STREAM") {
//流已经无效,不需要再重连
loger.warn("流已经无效->不需要再重连", err);
return;
}
if (err == "PEERCONNECTION_FAILED") {
setTimeout(()=> {
loger.warn("连接远程的流失败->尝试重新连接", err);
this.reAddRemoteStream(_stream);
}, 1200);
} else {
loger.warn("添加一个远程视频流->失败", err);
}
});
}
//尝试添加远程的移动设备视频流
tryAddMobileStream(nodeId) {
let stream = this.remoteVideoList[nodeId];
if (!stream) {
return;
}
let remoteView = document.getElementById(this.xdyRemote + nodeId);
//console.log("remoteView->", remoteView)
if (remoteView) {
let player = document.getElementById("player_" + nodeId);
let len = $("#" + this.xdyRemote + nodeId + " #player_" + nodeId).length;
if (len > 0) {
loger.log(nodeId + " 流已经添加显示,不需要再处理");
return;
} else {
loger.log(nodeId + " 删除无效的视图->创建新的视图remoteView");
remoteView.remove();
}
}
if (stream) {
loger.log("收到移动端推流的消息,主动添加一个远程视频流");
this.addRemoetStreamView(stream);
}
}
joinChannel(_params) {
if (!this.client) {
loger.warn("入视频通话频道->失败->未初始化对象");
return;
}
this.channelId = _params.channelId || "";
this.uid = parseInt(_params.uid) || 0;
this.info = _params.info || "";
this.channelKey = _params.channelKey || null;
//记录加入频道成功之后是否立即推流,默认false
//一般只有在刷新重进频道的时候会用到
this.immediatePublish = _params.immediatePublish || false;
this.isEnableVideo = true;
this.isEnableAudio = true;
GlobalConfig.videoEnabled = true;
GlobalConfig.audioEnabled = true;
//根据不同身份设置不同的分辨率
if (GlobalConfig.isTeachOrAssistant) {
if (GlobalConfig.maxMediaChannels == 1) {
//直播时使用标清最高档
this.videoResolution = "360P_8";
} else {
this.videoResolution = "240P";
}
} else if (GlobalConfig.isInvisible) {
this.videoResolution = "120P";
} else {
//学生在两路视频的时候使用240P 其他多人课堂的时候使用低清的
if (GlobalConfig.maxMediaChannels == 2 || GlobalConfig.maxMediaChannels > 3) {
this.videoResolution = "240P"
} else {
//180P_4 13 240x180 15 120
this.videoResolution = "180P_4"
}
}
loger.log("开始加入视频通话频道->channelId:" + this.channelId, "uid:" + this.uid, "videoResolution:" + this.videoResolution);
this.client.join(this.channelKey, "" + this.channelId, this.uid, (uid)=> {
this.uid = uid;
loger.log("加入视频通话频道->成功->channelId:" + this.channelId, "uid:" + this.uid);
this.isWebSocketDisconnect = false;
this._emit(MessageTypes.WEB_RTC_JOIN_SUCCESS);
this.openLoaclStream();
//加入频道成功之后需要判断是否立即开启推流
if (this.immediatePublish == true) {
loger.log("加入音视频频道成功->立刻开始推流->" + this.immediatePublish);
clearTimeout(this.rePublishDelay);
this.rePublishDelay = setTimeout(()=> {
this.publish();
}, 400);
}
}, (err)=> {
loger.error("加入视频通话频道->失败->", err);
this._emit(MessageTypes.WEB_RTC_JOIN_FAILED);
});
}
//重新获取摄像头和麦克风并重新推流
reGetLoaclStream() {
if (this.isPublish) {
loger.log("重新获取摄像头和麦克风并重新推流");
//this.changePublishStatusAndServerRecord(WebRtcApe.RECORD_STATUS_0);
this.unpublish();
this.openLoaclStream();
//切换设备后自动重推流
this.rePublishDelay = setTimeout(()=> {
this.publish();
}, 1200);
} else {
this.openLoaclStream();
}
}
openLoaclStream() {
/* if(this.localStream){
this.localStream.close();
this.localStream=null;
}*/
loger.log("获取本地视频流");
this.localStream = AgoraRTC.createStream({
streamID: this.uid,
audio: true,
microphoneId: this.curMicrophoneId,
cameraId: this.curCameraId,
video: this.isOpenVideo,
screen: false
});
this.localStream.on("accessAllowed", function () {
loger.warn("摄像头麦克风->已经获取权限");
})
// The user has denied access to the camera and mic.
this.localStream.on("accessDenied", function () {
loger.warn("摄像头和麦克风->权限获取失败");
})
if (this.isOpenVideo) {
loger.log("摄像头已经获取->设置本地视频分辨率:" + this.videoResolution);
//设置视频分辨率
this.localStream.setVideoProfile(this.videoResolution);
} else {
//没有视频,设置为最低
loger.log("摄像头没有获取到->设置本地流分辨率:120P");
this.localStream.setVideoProfile("120P");
}
}
leaveChannel() {
loger.log("调用离开视频通话频道->isPublish:" + this.isPublish);
this._emit(MessageTypes.WEB_RTC_LEAVE_CHANNEL);
if (!this.client) {
return;
}
this.firstPublishSuccess = false;
this.unpublish();
this.client.leave(() => {
loger.log("离开视频通话频道->成功");
}, (err)=> {
loger.log("离开视频通话频道->失败");
});
this.clearAllRemoteView();
}
closeRemoteVideoView(_data) {
if (!_data) {
return;
}
//根据nodeId查找视频
try {
//loger.log("立即删除停止推流人员的视图");
$('#' + this.xdyRemote + _data.nodeId).remove();
} catch (err) {
}
}
/*
* 设置旁录地址
* */
setConfigPublisherUrl(_publishUrl) {
this.firstPublishSuccess = false;
this.setConfigTimestamp = new Date().getTime() / 1000;
this.configPublisherUrl = _publishUrl;
if (this.client && this.configPublisherUrl) {
let configObj = {
width: parseInt(this.pWidth),
height: parseInt(this.pHeight),
framerate: parseInt(this.pFrameRate),
bitrate: parseInt(this.pBitrate),
publishUrl: "" + this.configPublisherUrl
};
//let configObj={width: 480, height:360, framerate:30, bitrate:500, publishUrl:_publishUrl};
//let configObj={width: 480, height:360, framerate:30, bitrate:500, publishUrl:'rtmp://txlivepush.xuedianyun.com/live/markettest_395312484_T8440_983041_1507888360?bizid=11220&txSecret=15cc50d93f86f9e1a2a76a10db2b09a8&txTime=59e135a8&record=hls|flv&record_interval=5400'};
loger.warn("设置旁路地址->", configObj);
this.client.configPublisher(configObj);
} else {
loger.warn("设置旁路地址->失败->为初始化或旁路地址无效", _publishUrl);
}
}
/*
* 设置旁录拉流地址
* */
setRtmpM3u8Path(_param) {
//_webRtc.setRtmpM3u8Path({m3u8Url:m3u8Stream,rtmpUrl:rtmpStream});
loger.log("设置旁录拉流地址", _param);
if (_param) {
this.m3u8Url = _param.m3u8Url || "";
this.rtmpUrl = _param.rtmpUrl || "";
}
}
publish(_params) {
if (!this.client) {
loger.warn("推流失败->未加入频道!");
return;
}
if (!this.localStream) {
loger.warn("推流失败->本地流获取失败!->尝试重新获取本地流");
this.openLoaclStream();
return;
}
//老师-助教-主讲人-->设置旁路大于30秒没有推流,推流服务会停止,需要重设旁录和重加频道;
if (this.setConfigTimestamp > 0 && GlobalConfig.isTeachOrAssistant) {
//如果间隔大于28秒并且没有推过流需要重新加入频道,推成功一次之后就不需要
let interval = parseInt(new Date().getTime() / 1000 - this.setConfigTimestamp);
loger.log("设置旁路的时间和推流时间的间隔->" + interval + "秒 firstPublishSuccess:" + this.firstPublishSuccess);
if (interval >= 28 && !this.firstPublishSuccess) {
loger.warn("设置旁路大于30秒没有推流,推流服务会停止,需要重设旁录和重加频道");
this._emit(WebRtcApe.RE_JOIN_CHANNEL, {publish: true});
return;
}
}
this.localStream.init(()=> {
this.clearLocalView();
let viewName = 'localVideoBox_' + this.uid;
let videoBox = document.createElement("div");
videoBox.id = viewName;
videoBox.className = this.localWebRtcVideoClass;
videoBox.style.width = (this.localVideoWidth * this.videoScale) + 'px';
videoBox.style.height = (this.localVideoHeight * this.videoScale) + 'px';
videoBox.style.float = 'left';
videoBox.style.marginRight = "1px";
videoBox.style.pointerEvents = 'none';
//自己的视图往前添加
$(this.localViewId).prepend(videoBox);
$("#" + viewName).css("transform", 'rotateY(180deg)');
let audioPlayIcoBox = `<div class="audioPlayIcoBox " id=${"audioPlayIcoBox" + this.uid} ></div>`;
$("#" + viewName).append(audioPlayIcoBox);
//显示自己的名字
let user = GlobalConfig.getUserInfoFromeNodeId(this.uid);
let userName = "";
if (user) {
userName = user.name || "";
}
let audioMutedDiv = "";
let videoMutedDiv = "";
let videoAndAudioBox = ""
if (GlobalConfig.isTeachOrAssistant) {
videoMutedDiv = `<div class="audioAndVideMuted cameraOn " id=${this.videoMutedIdName + this.uid} title="${this.closeCameraTitle}"></div>`;
audioMutedDiv = `<div class="audioAndVideMuted microphoneOn " id=${this.audioMutedIdName + this.uid} title="${this.closeMicrophoneTitle}"></div>`;
videoAndAudioBox = `<div class="audioAndVideBox openVideo">${videoMutedDiv + audioMutedDiv}</div>`;
}
let nameDiv = `<div id="${"videoOwnerName_" + this.uid}" class="localVideoOwnerName" style="width:${this.localVideoWidth}px;height:26px; position: absolute;bottom: 2px; z-index: 1;overflow:hidden;font-size: 14px;text-align: right; vertical-align:bottom;color: #e7e7e7;display:${this.nameDisplay}">${userName + videoAndAudioBox}</div>`;
$(this.localViewId).prepend(nameDiv);
$("#" + this.videoMutedIdName + this.uid).off("click", this._clickVideoMuted.bind(this));
$("#" + this.audioMutedIdName + this.uid).off("click", this._clickAudioMuted.bind(this));
$("#" + this.videoMutedIdName + this.uid).on("click", this._clickVideoMuted.bind(this));
$("#" + this.audioMutedIdName + this.uid).on("click", this._clickAudioMuted.bind(this));
loger.log("webRtc->推流->", viewName, new Date().getTime());
this.localStream.play(viewName);
this.client.publish(this.localStream, (err)=> {
loger.log("webRtc->推流失败: " + err);
//this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type:"error",msg:err.msg||err});
this._publishError(err.msg || err);
this.isPublish = false;
this.unpublish();
});
}, (err)=> {
loger.warn("webRtc->推流->本地流开启失败", err);
this.isPublish = false;
this.clearLocalView();
this._publishError(err.msg || err);
});
}
/*
* 推流失败
* */
_publishError(_msg) {
switch (_msg) {
case "DEVICES_NOT_FOUND":
if (this.cameras.length < 1 && this.microphones.length < 1) {
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: "DEVICES_NOT_FOUND"});
} else if (this.cameras.length < 1 && this.microphones.length >0) {
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: "DEVICES_NOT_FOUND_CAMERA"});
} else if (this.cameras.length >0 && this.microphones.length < 1) {
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: "DEVICES_NOT_FOUND_MIC"});
}
this.curCameraId = "";
this.curMicrophoneId = "";
this.unpublish();
break;
case "NOT_SUPPORTED":
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: _msg});
this.curCameraId = "";
this.curMicrophoneId = "";
this.unpublish();
break;
case "PERMISSION_DENIED":
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: _msg});
this.curCameraId = "";
this.curMicrophoneId = "";
this.unpublish();
break;
case "CONSTRAINT_NOT_SATISFIED":
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: _msg});
this.curCameraId = "";
this.curMicrophoneId = "";
this.unpublish();
break;
case "STREAM_ALREADY_INITIALIZED":
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: _msg});
this.curCameraId = "";
this.curMicrophoneId = "";
this.unpublish();
break;
default:
this._emit(MessageTypes.WEB_RTC_PUBLISH_FAILED, {type: "error", msg: _msg});
break
}
}
unpublish() {
clearTimeout(this.rePublishDelay);
if (!this.client) {
loger.log("webRtc->停止推流失败->没有加入频道", new Date().getTime());
return;
}
if (!this.localStream) {
loger.log("webRtc->停止推流失败->没有本地视频流", new Date().getTime());
return;
}
loger.log("webRtc->停止推流 ", new Date().getTime());
this.client.unpublish(this.localStream, (err)=> {
loger.log("webRtc->停止推流->失败" + err);
});
this.localStream.close();
this.clearLocalView();
this.isPublish = false;
this.isEnableVideo = true;
this.isEnableAudio = true;
GlobalConfig.videoEnabled = true;
GlobalConfig.audioEnabled = true;
GlobalConfig.openCamera = 0;
GlobalConfig.openMicrophones = 0;
this._emit(MessageTypes.USER_DEVICE_STATUS_CHAANGE, {
nodeId: GlobalConfig.nodeId,
userRole: GlobalConfig.userRole,
userName: GlobalConfig.userName,
userId: GlobalConfig.userId,
openCamera: GlobalConfig.openCamera,
openMicrophones: GlobalConfig.openMicrophones
});
}
//清除本地视图
clearLocalView() {
loger.log("清除本地视图");
$('#localVideoBox_' + this.uid).remove();
$("#videoOwnerName_" + this.uid).remove();
$(".localVideoOwnerName").remove();
$("." + this.localWebRtcVideoClass).remove();
}
//清除所有远程视图
clearAllRemoteView() {
loger.log("清除所有远程视图");
$("." + this.localWebRtcVideoClass).remove();
$("." + this.hostWebRtcVideoClass).remove();
$("." + this.normalWebRtcVideoClass).remove();
}
/*
* 更新所有视频的尺寸大小
* */
updateAllVideoSize() {
$("." + this.localWebRtcVideoClass).css("width", this.localVideoWidth * this.videoScale);
$("." + this.localWebRtcVideoClass).css("height", this.localVideoHeight * this.videoScale);
$("#videoOwnerName_" + this.uid).css("width", this.localVideoWidth * this.videoScale);
$("." + this.hostWebRtcVideoClass).css("width", this.hostRemoteVideoWidth * this.videoScale);
$("." + this.hostWebRtcVideoClass).css("height", this.hostRemoteVideoHeight * this.videoScale);
$("." + this.normalWebRtcVideoClass).css("width", this.normalRemoteVideoWidth * this.videoScale);
$("." + this.normalWebRtcVideoClass).css("height", this.normalRemoteVideoHeight * this.videoScale);
}
/*
* 设置rtc视频的属性
* */
changeRtcVideoConfig(_params) {
//{videoScale:1}
if (!_params) {
return;
}
let scale = parseInt(_params.videoScale) || 1;//最小值只能为1,这个是按倍数缩放视频
if (this.videoScale == scale) {
return;
}
this.videoScale = scale;
loger.log("更新视频视图大小->videoScale:" + this.videoScale);
this.updateAllVideoSize();
}
/*
* 设置本地回显视图
* */
setLoaclView(_params) {
loger.log("设置自己本地回显视图");
this.localViewId = _params.divId || "";
this.localStyle = _params.styleStr || "";
this.localVideoWidth = parseInt(_params.width) || SIZE_480;
this.localVideoHeight = parseInt(_params.height) || SIZE_360;
this.nameDisplay = _params.nameDisplay || "block";
this.localVideoWidth = this.localVideoWidth;
this.localVideoHeight = this.localVideoHeight;
}
/*
* 设置其他人的video视图容器
* */
setHostRemoteMediaView(_params) {
loger.log("设置老师视图容器");
this.hostRemoteViewId = _params.divId || "";
this.hostRemoteStyle = _params.styleStr || "";
this.hostRemoteVideoWidth = parseInt(_params.width) || SIZE_480;
this.hostRemoteVideoHeight = parseInt(_params.height) || SIZE_360;
this.hostRemoteVideoWidth = this.hostRemoteVideoWidth;
this.hostRemoteVideoHeight = this.hostRemoteVideoHeight;
}
/*
* 设置其他人的video视图容器
* */
setNormalRemoteMediaView(_params) {
loger.log("设置学生视图容器");
this.normalRemoteViewId = _params.divId || "";
this.normalRemoteStyle = _params.styleStr || "";
this.normalRemoteVideoWidth = parseInt(_params.width) || SIZE_480;
this.normalRemoteVideoHeight = parseInt(_params.height) || SIZE_360;
this.normalRemoteVideoWidth = this.normalRemoteVideoWidth;
this.normalRemoteVideoHeight = this.normalRemoteVideoHeight;
}
/*
* 设置隐藏用户的video视图容器
* */
setInvisibleMediaView(_params) {
loger.log("设置监课视图容器");
this.invisibleViewId = _params.divId || "";
this.invisibleStyle = _params.styleStr || "";
this.invisibleVideoWidth = parseInt(_params.width) || SIZE_480;
this.invisibleVideoHeight = parseInt(_params.height) || SIZE_360;
}
/*
* 设置旁录推流的参数
* */
setConfigPublisher(_params) {
loger.log("设置旁录推流的参数", _params);
this.pWidth = _params.width || SIZE_480;
this.pHeight = _params.height || SIZE_360;
this.pFrameRate = _params.frameRate || 30;
this.pBitrate = _params.bitrate || 500;
}
/*
* 切换当前使用的设备
* */
changeDevices(_params) {
loger.log("切换设备->", _params);
if (!_params) {
return;
}
//设置摄像头
if (_params.curCamera) {
for (let k in this.cameras) {
let item = this.cameras[k];
if (item && item.label == _params.curCamera) {
this.curCameraId = item.deviceId;
GlobalConfig.curCamera = _params.curCamera;
break;
}
}
}
//设置麦克风
if (_params.curMicrophone) {
for (let k in this.microphones) {
let item = this.microphones[k];
if (item && item.label == _params.curMicrophone) {
this.curMicrophoneId = item.deviceId;
GlobalConfig.curMicrophone = _params.curMicrophone;
break;
}
}
}
//分辨率
if (_params.videoResolution) {
this.videoResolution = _params.videoResolution || this.videoResolution;//默认是240P 20 320x240 15 200
}
clearTimeout(this.changeDevicesDelay);
this.changeDevicesDelay = setTimeout(()=> {
this.changePublishStatusAndServerRecord(WebRtcApe.RECORD_STATUS_0);
//重新获取本地视图流
this.reGetLoaclStream();
}, 1400);
}
/*
* 获取设备信息
* */
getDevices(_params, _callback) {
AgoraRTC.getDevices((devices)=> {
//下面的数组存的是对象
this.microphones = [];
this.cameras = [];
//选的数组存的是设备名称
GlobalConfig.cameras = [];
GlobalConfig.microphones = [];
loger.log("devices", devices)
for (let i = 0; i < devices.length; i++) {
let device = devices[i];
//{"deviceId":"default","kind":"audiooutput","label":"默认","groupId":"cf49a03ca26700235629fc13d3e6630bd34407c66438d157056a34dd3ae03ef5"}
if (device) {
if (device.kind == 'audioinput') {
this.microphones.push(device);
GlobalConfig.microphones.push(device.label || "microphone" + i);
} else if (device.kind == 'videoinput') {
this.cameras.push(device);
GlobalConfig.cameras.push(device.label || "camera" + i);
} else {
loger.warn('其他设备: ', device);
}
}
}
if (GlobalConfig.cameras && GlobalConfig.cameras.length < 1) {
this.isOpenVideo = false;
} else {
this.isOpenVideo = true;
}
let _deviceData = {cameras: GlobalConfig.cameras, microphones: GlobalConfig.microphones};
if (_callback) {
_callback(_deviceData);
}
this._emit(MessageTypes.GET_DEVICES_SUCCESS, _deviceData);
});
}
/*
*
* 点击禁用和开启视频
* */
_clickVideoMuted(evt) {
let className = evt.currentTarget.className;
let idArr = (evt.currentTarget.id).split("_");
let uid = 10000000;//默认设置一个不存在的uid
if (idArr && idArr.length > 1) {
uid = parseInt(idArr[1]);
}
let user = GlobalConfig.getUserInfoFromeNodeId(parseInt(uid));
let userName = "";
let roleRole = "";
if (user) {
roleRole = GlobalConfig.getUserRoleToString(user.role);
userName = user.name;
}
if (className.indexOf("cameraOn") > 0) {
loger.log("点击禁用视频按钮->用户:[" + roleRole + "] " + userName + " uid:" + uid);
this.sendChangeUserMediaEnabled({nodeId: uid, video: false, audio: true});
} else {
loger.log("点击解除视频禁用按钮->用户:[" + roleRole + "] " + userName + " uid:" + uid);
this.sendChangeUserMediaEnabled({nodeId: uid, video: true, audio: true});
}
}
/*
* 点击禁音和开启按钮切换
* */
_clickAudioMuted(evt) {
let className = evt.currentTarget.className;
let idArr = (evt.currentTarget.id).split("_");
let uid = 10000000;//默认设置一个不存在的uid
if (idArr && idArr.length > 1) {
uid = parseInt(idArr[1]);
}
let user = GlobalConfig.getUserInfoFromeNodeId(parseInt(uid));
let userName = "";
let roleRole = "";
if (user) {
roleRole = GlobalConfig.getUserRoleToString(user.role);
userName = user.name;
}
if (className.indexOf("microphoneOn") > 0) {
loger.log("点击禁音按钮->用户:[" + roleRole + "] " + userName + " uid:" + uid);
this.sendChangeUserMediaEnabled({nodeId: uid, video: true, audio: false});
} else {
loger.log("点击解除禁音按钮->用户:[" + roleRole + "] " + userName + " uid:" + uid);
this.sendChangeUserMediaEnabled({nodeId: uid, video: true, audio: true});
}
}
/*
* 发送控制音视频禁用消息
* */
sendChangeUserMediaEnabled(_param) {
this._emit(MessageTypes.MEDIA_ENABLED_CHANGE, _param);
}
/*
* 收到控制音视频禁用消息 {nodeId: uid, video: true, audio: false}
* */
receiveWebRtcMeiaEnabledChange(_data) {
loger.log("收到控制音视频禁用消息", _data, "myNodeId:" + GlobalConfig.nodeId + " isEnableVideo:" + this.isEnableVideo + " isEnableAudio:" + this.isEnableAudio);
if (!_data) {
return;
}
if (_data.nodeId != GlobalConfig.nodeId) {
//不是自己的只设置状态显示即可
//音频
this.setUidAudioEnabledStatus(_data.nodeId, Boolean(_data.audio));
//视频
this.setUidVideoEnabledStatus(_data.nodeId, Boolean(_data.video));
} else {
//控制自己的音频
if (this.isEnableVideo == _data.video && this.isEnableAudio == _data.audio) {
loger.log("收到控制音视频禁用消息->自己当前状态一不需要设置:", _data);
//音频
this.setUidAudioEnabledStatus(_data.nodeId, Boolean(_data.audio));
//视频
this.setUidVideoEnabledStatus(_data.nodeId, Boolean(_data.video));
return;
}
//记录自己当前的音视频禁用状态
this.isEnableVideo = _data.video;
this.isEnableAudio = _data.audio;
if (_data.audio == false) {
this.disableAudio(_data.nodeId);
} else {
this.enableAudio(_data.nodeId);
}
//控制自己的视频
if (_data.video == false) {
this.disableVideo(_data.nodeId);
} else {
this.enableVideo(_data.nodeId);
}
//更新同步用户的媒体禁用状态
//loger.log("更新同步用户的媒体禁用状态", _data);
if (_data) {
this._emit(WebRtcApe.UPDATE_USER_MEDIA_MUTED_STATUS, _data);
}
}
}
/*
* 开启禁音
* */
disableAudio(uid) {
if (parseInt(uid) == GlobalConfig.nodeId) {
loger.log("开启禁音:" + uid);
if (this.localStream) {
this.setUidAudioEnabledStatus(uid, false);
this.localStream.disableAudio();
}
}
}
/*
* 开启音频
* */
enableAudio(uid) {
if (parseInt(uid) == GlobalConfig.nodeId) {
loger.log("开启音频:" + uid);
if (this.localStream) {
this.localStream.enableAudio();
this.setUidAudioEnabledStatus(uid, true);
}
}
}
/*
* 设置音频禁用按钮的状态
* uid nodeId
* isEnable true开启 false 禁用
*
* */
setUidAudioEnabledStatus(uid, isEnable) {
if (isEnable == true) {
loger.log("设置音频禁用按钮的状态", uid, "开启");
$("#" + this.audioMutedIdName + uid).removeClass("microphoneOff");
$("#" + this.audioMutedIdName + uid).addClass("audioAndVideMuted microphoneOn");
$("#" + this.audioMutedIdName + uid).attr("title", this.closeMicrophoneTitle);
} else {
loger.log("设置音频禁用按钮的状态", uid, "禁用");
$("#" + this.audioMutedIdName + uid).removeClass("microphoneOn");
$("#" + this.audioMutedIdName + uid).addClass("audioAndVideMuted microphoneOff");
$("#" + this.audioMutedIdName + uid).attr("title", this.openMicrophoneTitle);
}
}
/*
* 禁用摄像头
* */
disableVideo(uid) {
if (parseInt(uid) == GlobalConfig.nodeId) {
loger.log("禁用摄像头:" + uid);
if (this.localStream) {
this.setUidVideoEnabledStatus(uid, false);
this.localStream.disableVideo();
}
}
}
/*
* 开启摄像头
* */
enableVideo(uid) {
if (parseInt(uid) == GlobalConfig.nodeId) {
if (this.localStream) {
loger.log("开启摄像头:" + uid);
this.localStream.enableVideo();
this.setUidVideoEnabledStatus(uid, true);
}
}
}
/*
* 设置视频禁用按钮的状态
* uid nodeId
* isEnable true开启 false 禁用
*
* */
setUidVideoEnabledStatus(uid, isEnable) {
let user = GlobalConfig.getUserInfoFromeNodeId(parseInt(uid));
if (user && user.cameras && user.cameras.length < 1) {
//用户没有摄像头 显示音频封面
$("#audioPlayIcoBox" + uid).show();
$("#" + this.videoMutedIdName + uid).hide();
loger.log("设置视频禁用按钮的状态->没有摄像头不需要设置", uid, isEnable)
return;
}
if (isEnable == true) {
//开启
loger.log("设置视频禁用按钮的状态", uid, "开启");
$("#audioPlayIcoBox" + uid).hide();
$("#" + this.videoMutedIdName + uid).removeClass("cameraOff");
$("#" + this.videoMutedIdName + uid).addClass("audioAndVideMuted cameraOn");
$("#" + this.videoMutedIdName + uid).attr("title", this.closeCameraTitle);
} else {
//禁用
loger.log("设置视频禁用按钮的状态", uid, "禁用");
$("#audioPlayIcoBox" + uid).show();
$("#" + this.videoMutedIdName + uid).removeClass("cameraOn");
$("#" + this.videoMutedIdName + uid).addClass("audioAndVideMuted cameraOff");
$("#" + this.videoMutedIdName + uid).attr("title", this.openCameraTitle);
}
}
//组织数据,发送给服务器,控制录制和开启录制-推流和停止推流 status:0 停止推流 1:开始推流(同时开启录制),2:停止录制(同时停止推流)
packMediaInfoData(_status) {
let curTimestamp = new Date().getTime();
let data = `appId=${GlobalConfig.appId}&channel=${GlobalConfig.channelId}&channelKey=${GlobalConfig.appCertificate}&uid=${GlobalConfig.userUid}&status=${_status}&userId=${GlobalConfig.userId}&userName=${GlobalConfig.userName}&userRole=${GlobalConfig.userRole}×tamp=${curTimestamp}&recordTimestamp=${GlobalConfig.recordTimestamp}`;
//markettest_623790840_T9540_1508207080
let streamId = GlobalConfig.siteId + "_" + GlobalConfig.classId + "_" + GlobalConfig.userId + "_" + curTimestamp;
//mcu记录一份数据
this._emit(MessageTypes.MEDIA_PUBLISH_STATUS_CHANGE, {
appId: GlobalConfig.appId,
channel: GlobalConfig.channelId,
channelKey: GlobalConfig.appCertificate,
uid: GlobalConfig.userUid,
status: _status,
userId: GlobalConfig.userId,
userName: GlobalConfig.userName,
userRole: GlobalConfig.userRole,
timestamp: curTimestamp,
recordTimestamp: GlobalConfig.recordTimestamp,
streamId: streamId,
publishUrl: this.configPublisherUrl,
m3u8Url: this.m3u8Url,
rtmpUrl: this.rtmpUrl
});
return data;
}
//调用服务端接口
//调用推流/停止推流->并且告诉服务器端开启录制
//status:0 停止推流 1:开始推流(同时开启录制),2:停止录制(同时停止推流)
changePublishStatusAndServerRecord(_status) {
if (!GlobalConfig.recordInterfaces) {
loger.log("调用服务器端更新视频录制状态->失败->接口地址无效");
return;
}
let url = GlobalConfig.locationProtocol + GlobalConfig.recordInterfaces;
let data = this.packMediaInfoData(_status);
loger.log("调用服务器端更新视频录制状态->status", _status);
fetch(encodeURI(url), {
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: data,
timeout: 4000
})
.then(ret => {
if (ret.ok) {
return ret.json();
} else {
loger.error(`调用服务器端更新视频录制状态-网络异常.状态码:${ret.status}`);
throw '';
}
})
.then(ret => {
if (ret) {
loger.log('调用服务器端更新视频录制状态', ret);
} else {
loger.warn('调用服务器端更新视频录制状态 失败.', ret);
}
})
.catch(err => {
loger.error(`调用服务器端更新视频录制状态.状态码:${err}`);
});
}
/*
* 切换音视频的录制状态
* */
changeMediaRecordStatus(_params) {
if (!GlobalConfig.recordInterfaces || !_params) {
loger.warn("切换音视频的录制状态->失败->接口地址无效", _params);
return;
}
loger.warn("切换音视频的录制状态->" + _params);
let url = GlobalConfig.locationProtocol + GlobalConfig.recordInterfaces;
let curTimestamp = new Date().getTime();
let data = `appId=${GlobalConfig.appId}&channel=${GlobalConfig.channelId}&channelKey=${GlobalConfig.appCertificate}&uid=${GlobalConfig.userUid}&status=${_params.status}&userId=${GlobalConfig.userId}&userName=${GlobalConfig.userName}&userRole=${GlobalConfig.userRole}×tamp=${curTimestamp}&recordTimestamp=${GlobalConfig.recordTimestamp}`;
fetch(encodeURI(url), {
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: data,
timeout: 4000
})
.then(ret => {
if (ret.ok) {
return ret.json();
} else {
loger.error(`切换音视频的录制状态-网络异常.状态码:${ret.status}`);
throw '';
}
})
.then(ret => {
if (ret) {
loger.log('切换音视频的录制状态->完成', ret);
} else {
loger.warn('切换音视频的录制状态 失败.', ret);
}
})
.catch(err => {
loger.error(`切换音视频的录制状态.状态码:${err}`);
});
}
}
WebRtcApe.prototype.RECORD_STATUS_0 = WebRtcApe.RECORD_STATUS_0 = 0; //停止推流
WebRtcApe.prototype.RECORD_STATUS_1 = WebRtcApe.RECORD_STATUS_1 = 1; //开始推流
WebRtcApe.prototype.RECORD_STATUS_2 = WebRtcApe.RECORD_STATUS_2 = 2; //停止录制
WebRtcApe.prototype.RE_JOIN_CHANNEL = WebRtcApe.RE_JOIN_CHANNEL = "reJoninChanel";//重加入频道
WebRtcApe.prototype.UPDATE_USER_MEDIA_MUTED_STATUS = WebRtcApe.UPDATE_USER_MEDIA_MUTED_STATUS = "updateUserMediaMutedStatus";
export default new WebRtcApe;