How to use mergeStreams method in Playwright Internal

Best JavaScript code snippet using playwright-internal

mlvbliveroomcore.js

Source:mlvbliveroomcore.js Github

copy

Full Screen

1/**2 * @file liveroom.js 直播模式房间管理sdk3 * @author binniexu4 */5var webim = require('webim_wx');6var webimhandler = require('webim_handler');7//移动直播(<mlvb-live-room>)使用此地址实现房间服务和连麦功能8var RoomServiceUrl = "https://liveroom.qcloud.com/weapp/live_room/",9 heart = '', // 判断心跳变量10 requestSeq = 0, // 请求id11 requestTask = [], // 请求task12 // 用户信息13 accountInfo = {14 userID: '', // 用户ID15 userName: '', // 用户昵称16 userAvatar: '', // 用户头像URL17 userSig: '', // IM登录凭证18 sdkAppID: '', // IM应用ID19 accountType: '', // 账号集成类型20 accountMode: 0, //帐号模式,0-表示独立模式,1-表示托管模式21 token: '' //登录RoomService后使用的票据22 },23 // 房间信息24 roomInfo = {25 roomID: '', // 视频位房间ID26 roomInfo: '', // 房间名称27 mixedPlayURL: '', // 混流地址28 isCreator: false, // 是否为创建者29 pushers: [], // 当前用户信息30 isLoginIM: false, // 是否登录IM31 isJoinGroup: false, // 是否加入群32 isDestory: false, // 是否已解散33 hasJoinAnchor: false,34 roomStatusCode: 035 },36 // 事件37 event = {38 onAnchorEnter: function () {}, // 进房通知39 onAnchorExit: function () {}, // 退房通知40 onRoomDestroy: function() {}, // 群解散通知41 onRecvRoomTextMsg: function() {}, // 消息通知42 onRequestJoinAnchor: function() {}, //大主播收到小主播连麦请求通知43 onKickoutJoinAnchor: function() {}, //小主播被踢通知44 onRecvRoomCustomMsg: function() {}, //自定义消息通知45 onSketchpadData: function(){}46 };47// 随机昵称48var userName = ['林静晓', '陆杨', '江辰', '付小司', '陈小希', '吴柏松', '肖奈', '芦苇微微', '一笑奈何', '立夏'];49// 请求数50var requestNum = 0;51var requestJoinCallback = null;52var bigAnchorStreamID = '';53var bigAnchorWidth = 360;54var bigAnchorHeight = 640;55var gTimeoutID = null;56var mTimeDiff = 0;57/**58 * [request 封装request请求]59 * @param {options}60 * url: 请求接口url61 * data: 请求参数62 * success: 成功回调63 * fail: 失败回调64 * complete: 完成回调65 */66function request(options) {67 requestNum++;68 console.log('requestNum: ', requestNum);69 requestTask[requestSeq++] = wx.request({70 url: RoomServiceUrl + options.url + (options.params?('?' + formatParams(options.params) + '&'):'?') + 'userID=' + accountInfo.userID + (accountInfo.token?'&token=' + accountInfo.token:""),71 data: options.data || {},72 method: 'POST',73 header: {74 'content-type': 'application/json' // 默认值75 },76 // dataType: 'json',77 success: options.success || function() {},78 fail: options.fail || function() {},79 complete: options.complete || function() {80 requestNum--;81 // console.log('complete requestNum: ',requestNum);82 }83 });84}85//url encode编码86function formatParams(data) {87 var arr = [];88 for (var name in data) {89 arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));90 }91 return arr.join("&");92}93function notifyPusherChange() {94 var customMsg = {95 cmd: "notifyPusherChange",96 data: {}97 }98 var strCustomMsg = JSON.stringify(customMsg);99 webimhandler.sendCustomMsg({data:strCustomMsg, text:"notify"}, null)100}101function mergeAnchors() {102 if (!roomInfo.hasJoinAnchor) {103 return;104 }105 getAnchors({106 data: {107 roomID: roomInfo.roomID108 },109 success: function(ret) {110 ret = ret.data;111 innerMergerAnchors(ret)112 },113 fail: function(ret) {114 // event.onRoomDestroy && event.onRoomDestroy({115 // errCode: ret.errCode,116 // errMsg: ret.errMsg117 // });118 }119 });120};121function innerMergerAnchors(data) {122 /**123 * enterPushers:新进推流人员信息124 * leavePushers:退出推流人员信息125 * ishave:用于判断去重操作126 */127 var enterPushers = [],leavePushers = [],ishave = 0;128 console.log('去重操作');129 console.log('旧', JSON.stringify(roomInfo.pushers));130 console.log('新',JSON.stringify(data.pushers));131 console.log('用户信息:', JSON.stringify(accountInfo));132 data.pushers && data.pushers.forEach(function(val1){133 ishave = 0;134 roomInfo.pushers && roomInfo.pushers.forEach(function(val2) {135 if(val1.userID == val2.userID) {136 ishave = 1;137 }138 });139 if(!ishave && val1.userID != accountInfo.userID)140 enterPushers.push(val1);141 ishave = 0;142 });143 roomInfo.pushers && roomInfo.pushers.forEach(function(val1) {144 ishave = 0;145 data.pushers && data.pushers.forEach(function(val2) {146 if(val1.userID == val2.userID) {147 ishave = 1;148 }149 });150 if(!ishave)151 leavePushers.push(val1);152 ishave = 0;153 });154 if (data.roomStatusCode) {155 roomInfo.roomStatusCode = data.roomStatusCode156 }157 // 重置roomInfo.pushers158 roomInfo.pushers = data.pushers;159 // 通知有人进入房间160 if(enterPushers.length) {161 console.log('进房:', JSON.stringify(enterPushers));162 event.onAnchorEnter && event.onAnchorEnter({163 pushers: enterPushers164 });165 //混流166 mergeStream(1);167 }168 // 通知有人退出房间169 if(leavePushers.length) {170 console.log('退房:', JSON.stringify(leavePushers));171 event.onAnchorExit && event.onAnchorExit({172 pushers: leavePushers173 });174 //混流175 mergeStream(1);176 }177}178function getAnchors(object) {179 var data = {};180 if (object.data && object.data.roomID) {181 data.roomID = object.data.roomID;182 } else if (roomInfo.roomID) {183 data.roomID = roomInfo.roomID;184 } else {185 object.fail && object.fail({186 errCode: -999,187 errMsg: '无roomID'188 })189 return;190 }191 //获取房间信息192 request({193 url: 'get_anchors',194 data: data,195 success: function (ret) {196 if (ret.data.code) {197 console.log('请求CGI:get_anchors失败', ret);198 object.fail && object.fail({errCode: ret.data.code, errMsg: '请求CGI:get_anchors失败:' + ret.data.message + + '[' + ret.data.code + ']'});199 return;200 }201 console.log("房间信息:", JSON.stringify(ret));202 object.success && object.success(ret);203 },204 fail: object.fail205 });206}207/**208 * [sendRoomTextMsg 发送文本消息]209 * @param {options}210 * data: {211 * msg: 文本消息212 * }213 */214function sendRoomTextMsg(options) {215 if (!options || !options.data.msg || !options.data.msg.replace(/^\s*|\s*$/g, '')) {216 console.log('sendRoomTextMsg参数错误',options);217 options.fail && options.fail({218 errCode: -9,219 errMsg: 'sendRoomTextMsg参数错误'220 });221 return;222 }223 webimhandler.sendCustomMsg({224 data: '{"cmd":"CustomTextMsg","data":{"nickName":"'+accountInfo.userName+'","headPic":"'+accountInfo.userAvatar+'"}}',225 text: options.data.msg226 },function() {227 options.success && options.success();228 });229}230/**231 * [pusherHeartBeat 推流者心跳]232 * @param {options}233 */234function pusherHeartBeat(options) {235 if (options) {236 setTimeout(function () {237 proto_pusherHeartBeat();238 }, 3000);239 }240 if (heart) {241 setTimeout(function () {242 proto_pusherHeartBeat();243 pusherHeartBeat();244 }, 7000);245 }246}247function proto_pusherHeartBeat() {248 console.log('心跳请求');249 request({250 url: 'anchor_heartbeat',251 data: {252 roomID: roomInfo.roomID,253 userID: accountInfo.userID,254 roomStatusCode: roomInfo.roomStatusCode255 },256 success: function (ret) {257 if (ret.data.code) {258 console.log('心跳失败:', ret);259 return;260 }261 if (ret.data.pushers) {262 innerMergerAnchors(ret.data);263 }264 console.log('心跳成功', ret);265 },266 fail: function (ret) {267 console.log('心跳失败:', ret);268 }269 });270}271/**272 * [stopPusherHeartBeat 停止推流者心跳]273 * @param {options}274 */275function stopPusherHeartBeat() {276 heart = false;277}278/**279 * [setListener 设置监听事件]280 * @param {options}281 * onRoomDestroy: 群解散通知282 * onRecvRoomTextMsg: 消息通知283 */284function setListener(options) {285 if (!options) { console.log('setListener参数错误',options); return; }286 event.onAnchorEnter = options.onAnchorEnter || function () {};287 event.onAnchorExit = options.onAnchorExit || function () {};288 event.onRoomDestroy = options.onRoomDestroy || function () {};289 event.onRecvRoomTextMsg = options.onRecvRoomTextMsg || function () {};290 event.onRequestJoinAnchor = options.onRequestJoinAnchor || function () {};291 event.onKickoutJoinAnchor = options.onKickoutJoinAnchor || function () {};292 event.onRecvRoomCustomMsg = options.onRecvRoomCustomMsg || function () {};293 event.onSketchpadData = options.onSketchpadData || function(){};294}295/**296 * [joinAnchor 加入推流]297 * @param {options}298 * data: {299 * roomID: 房间ID300 * pushURL: 推流地址301 * }302 * success: 成功回调303 * fail: 失败回调304 */305function joinAnchor(options) {306 if(!options || !options.data.roomID || !options.data.pushURL) {307 console.log('joinAnchor参数错误',options);308 options.fail && options.fail({309 errCode: -9,310 errMsg: 'joinAnchor参数错误'311 });312 return;313 }314 roomInfo.roomID = options.data.roomID;315 roomInfo.isDestory = false;316 proto_joinAnchor(options);317}318function proto_joinAnchor(options) {319 request({320 url: 'add_anchor',321 data: {322 roomID: roomInfo.roomID,323 userID: accountInfo.userID,324 userName: accountInfo.userName,325 userAvatar: accountInfo.userAvatar,326 pushURL: options.data.pushURL327 },328 success: function(ret) {329 if(ret.data.code) {330 console.log('进入房间失败:',ret);331 options.fail && options.fail({332 errCode: ret.data.code,333 errMsg: ret.data.message + '[' + ret.data.code + ']'334 });335 return;336 }337 roomInfo.hasJoinAnchor = true;338 mergeAnchors();339 console.log('加入推流成功');340 // 开始心跳341 heart = true;342 pusherHeartBeat(1);343 //通知房间内其他主播344 notifyPusherChange();345 options.success && options.success({roomID: roomInfo.roomID});346 },347 fail: function(ret) {348 console.log('进入房间失败:',ret);349 if(ret.errMsg == 'request:fail timeout') {350 var errCode = -1;351 var errMsg = '网络请求超时,请检查网络状态';352 }353 options.fail && options.fail({354 errCode: errCode || -4,355 errMsg: errMsg || '进入房间失败'356 });357 }358 });359}360/**361 * [clearRequest 中断请求]362 * @param {options}363 */364function clearRequest() {365 for(var i = 0; i < requestSeq; i++) {366 requestTask[i].abort();367 }368 requestTask = [];369 requestSeq = 0;370}371/**372 * [exitRoom 退出房间]373 * @param {options}374 */375function exitRoom(options) {376 if (roomInfo.isCreator) {377 destoryRoom(options);378 } else {379 leaveRoom(options);380 }381 roomInfo.isDestory = true;382 roomInfo.roomID = '';383 roomInfo.pushers = [];384 roomInfo.mixedPlayURL = "";385 roomInfo.roomInfo = "";386 accountInfo.pushURL = "";387 accountInfo.isCreator = false;388}389/**390 * [leaveRoom 退出房间]391 */392function leaveRoom(options) {393 // 停止心跳394 stopPusherHeartBeat();395 //通知房间内其他主播396 notifyPusherChange();397 // clearRequest();398 roomInfo.isJoinGroup && webimhandler.quitBigGroup();399 request({400 url: 'delete_anchor',401 data: {402 roomID: roomInfo.roomID,403 userID: accountInfo.userID404 },405 success: function(ret) {406 if(ret.data.code) {407 console.log('退出推流失败:',ret);408 console.error('退房信息: roomID:' + roomInfo.roomID + ", userID:" + accountInfo.userID);409 options.fail && options.fail({410 errCode: ret.data.code,411 errMsg: ret.data.message + '[' + ret.data.code + ']'412 });413 return;414 }415 console.log('退出推流成功');416 options.success && options.success({});417 },418 fail: function(ret) {419 console.log('退出推流失败:',ret);420 var errCode = ret.errCode || -1;421 var errMsg = ret.errMsg || '退出房间失败'422 if(ret.errMsg == 'request:fail timeout') {423 errCode = -1;424 errMsg = '网络请求超时,请检查网络状态';425 }426 options.fail && options.fail({427 errCode: errCode,428 errMsg: errMsg429 });430 }431 });432}433/**434 * [destoryRoom 销毁房间]435 */436function destoryRoom(options) {437 // 停止心跳438 stopPusherHeartBeat();439 // clearRequest();440 roomInfo.isJoinGroup && webimhandler.destroyGroup();441 if(roomInfo.isDestory) return;442 request({443 url: 'destroy_room',444 data: {445 roomID: roomInfo.roomID,446 userID: accountInfo.userID447 },448 success: function(ret) {449 if(ret.data.code) {450 console.log('关闭房间失败:',ret);451 console.error('关闭房间失败: roomID:' + roomInfo.roomID + ", userID:" + accountInfo.userID);452 options.fail && options.fail({453 errCode: ret.data.code,454 errMsg: ret.data.message + '[' + ret.data.code + ']'455 });456 return;457 }458 console.log('关闭房间成功');459 options.success && options.success({});460 },461 fail: function(ret) {462 console.log('关闭房间失败:',ret);463 var errCode = ret.errCode || -1;464 var errMsg = ret.errMsg || '关闭房间失败'465 if(ret.errMsg == 'request:fail timeout') {466 errCode = -1;467 errMsg = '网络请求超时,请检查网络状态';468 }469 options.fail && options.fail({470 errCode: errCode,471 errMsg: errMsg472 });473 }474 });475}476function quitJoinAnchor(options) {477 stopPusherHeartBeat();478 request({479 url: 'delete_anchor',480 data: {481 roomID: roomInfo.roomID,482 userID: accountInfo.userID483 },484 success: function(ret) {485 if(ret.data.code) {486 console.log('退出推流失败:',ret);487 options.fail && options.fail({488 errCode: ret.data.code,489 errMsg: ret.data.message + '[' + ret.data.code + ']'490 });491 return;492 }493 console.log('退出推流成功');494 roomInfo.pushers = [];495 //通知房间内其他主播496 notifyPusherChange();497 options.success && options.success({});498 },499 fail: function(ret) {500 console.log('退出推流失败:',ret);501 if(ret.errMsg == 'request:fail timeout') {502 var errCode = -1;503 var errMsg = '网络请求超时,请检查网络状态';504 }505 options.fail && options.fail({506 errCode: errCode || -1,507 errMsg: errMsg || '退出房间失败'508 });509 }510 });511 roomInfo.hasJoinAnchor = false;512}513function requestJoinAnchor (object) {514 var body = {515 cmd: 'linkmic',516 data: {517 type: 'request',518 roomID: roomInfo.roomID,519 userID: accountInfo.userID,520 userName: accountInfo.userName,521 userAvatar: accountInfo.userAvatar,522 timestamp: Math.round(Date.now()) - mTimeDiff523 }524 }525 requestJoinCallback = function(ret) {526 if (gTimeoutID) {527 clearTimeout(gTimeoutID);528 gTimeoutID = null;529 }530 if (ret.errCode) {531 object.fail && object.fail(ret);532 } else {533 object.success && object.success(ret);534 }535 }536 var isTimeout = false;537 gTimeoutID = setTimeout(function () {538 gTimeoutID = null;539 console.error('申请连麦超时:', JSON.stringify(object.data));540 isTimeout = true;541 requestJoinCallback && requestJoinCallback({542 errCode: -999,543 errMsg: '申请加入连麦超时'544 });545 }, (object.data && object.data.timeout)? object.data.timeout : 30000);546 var msg = {547 data: JSON.stringify(body)548 }549 webimhandler.sendC2CCustomMsg(roomInfo.roomCreator, msg, function (ret) {550 if (isTimeout) {551 return;552 }553 if (ret && ret.errCode) {554 console.log('请求连麦失败:', JSON.stringify(ret));555 requestJoinCallback && requestJoinCallback(ret);556 return;557 }558 });559}560function acceptJoinAnchor (object) {561 var body = {562 cmd: 'linkmic',563 data: {564 type: 'response',565 result: 'accept',566 reason: '',567 roomID: roomInfo.roomID,568 timestamp: Math.round(Date.now()) - mTimeDiff569 }570 }571 var msg = {572 data: JSON.stringify(body)573 }574 webimhandler.sendC2CCustomMsg(object.data.userID, msg, function (ret) {});575}576function rejectJoinAnchor (object) {577 var body = {578 cmd: 'linkmic',579 data: {580 type: 'response',581 result: 'reject',582 reason: object.data.reason || '主播拒绝了您的连麦请求',583 roomID: roomInfo.roomID,584 timestamp: Math.round(Date.now()) - mTimeDiff585 }586 }587 var msg = {588 data: JSON.stringify(body)589 }590 webimhandler.sendC2CCustomMsg(object.data.userID, msg, function (ret) {});591}592function kickoutJoinAnchor (object) {593 var body = {594 cmd: 'linkmic',595 data: {596 type: 'kickout',597 roomID: roomInfo.roomID,598 timestamp: Math.round(Date.now()) - mTimeDiff599 }600 }601 var msg = {602 data: JSON.stringify(body)603 }604 webimhandler.sendC2CCustomMsg(object.data.userID, msg, function (ret) {605 if (ret && ret.errCode==0) {606 object.success && object.success(ret);607 } else {608 object.fail && object.fail(ret);609 }610 });611}612function getAccountInfo() {613 return accountInfo;614}615/**616 *617 * @param {Int} retryCount618 */619function mergeStream(retryCount) {620 if (accountInfo.userID != roomInfo.roomCreator) {621 //大主播才能混流622 return;623 }624 var mergeStreams = [];625 if (roomInfo.pushers && roomInfo.pushers.length > 0) {626 roomInfo.pushers.forEach(function (val) {627 if (val.userID != roomInfo.roomCreator) {628 //获取流id629 var streamID = getStreamIDByStreamUrl(val.accelerateURL);630 if (streamID) {631 mergeStreams.push({632 userID: val.userID,633 streamID: streamID,634 width: val.width,635 height: val.height636 });637 }638 } else {639 bigAnchorStreamID = getStreamIDByStreamUrl(val.accelerateURL);640 }641 });642 }643 console.log("混流信息:", JSON.stringify(mergeStreams));644 sendStreamMergeRequest(retryCount, mergeStreams);645}646function getStreamIDByStreamUrl(streamUrl) {647 if (!streamUrl) {648 return null;649 }650 //推流地址格式: rtmp://8888.livepush.myqcloud.com/path/8888_test_12345?txSecret=aaa&txTime=bbb651 //拉流地址格式: rtmp://8888.livepush.myqcloud.com/path/8888_test_12345652 // http://8888.livepush.myqcloud.com/path/8888_test_12345.flv653 // http://8888.livepush.myqcloud.com/path/8888_test_12345.m3u8654 var subStr = streamUrl;655 var index = subStr.indexOf('?');656 if (index >= 0) {657 subStr = subStr.substring(0, index);658 }659 if (!subStr) {660 return null;661 }662 index = subStr.lastIndexOf('/');663 if (index >= 0) {664 subStr = subStr.substring(index + 1);665 }666 if (!subStr) {667 return null;668 }669 index = subStr.indexOf('.');670 if (index >= 0) {671 subStr = subStr.substring(0, index);672 }673 if (!subStr) {674 return null;675 }676 return subStr;677}678function sendStreamMergeRequest(retryCount, mergeStreams) {679 if (retryCount < 0) {680 return;681 }682 var mergeInfo = createMergeInfo(mergeStreams);683 console.log('混流信息:', JSON.stringify(mergeInfo));684 doMergeRequest(mergeInfo, function (ret) {685 if (ret) {686 console.log('混流成功');687 } else {688 console.log('混流失败');689 setTimeout(() => {690 retryCount--;691 sendStreamMergeRequest(retryCount, mergeStreams);692 }, 2000);693 }694 });695}696function doMergeRequest(mergeInfo, callback) {697 request({698 url: 'merge_stream',699 data: {700 userID: accountInfo.userID,701 roomID: roomInfo.roomID,702 mergeParams: JSON.stringify(mergeInfo)703 },704 success: function (ret) {705 if (ret.data.code || ret.data.merge_code) {706 console.error('混流失败:', JSON.stringify(ret));707 callback(false);708 return;709 }710 callback(true);711 },712 fail: function (ret) {713 callback(false);714 }715 })716}717function createMergeInfo(mergeStreams) {718 console.log("混流原始信息:", JSON.stringify(mergeStreams));719 var smallAnchorWidth = 160;720 var smallAnchorHeight = 240;721 var offsetHeight = 90;722 if (bigAnchorWidth < 540 || bigAnchorHeight < 960) {723 smallAnchorWidth = 120;724 smallAnchorHeight = 180;725 offsetHeight = 60;726 }727 //组装混流JSON结构体728 var streamInfoArray = [];729 if (mergeStreams && mergeStreams.length > 0) {730 //大主播731 var bigAnchorInfo = {732 input_stream_id: bigAnchorStreamID || '',733 layout_params: {734 image_layer: 1735 }736 }737 streamInfoArray.push(bigAnchorInfo);738 //小主播739 var subLocationX = bigAnchorWidth - smallAnchorWidth;740 var subLocationY = bigAnchorHeight - smallAnchorHeight - offsetHeight;741 if (mergeStreams && mergeStreams.length > 0) {742 var layerIndex = 0743 mergeStreams.forEach(function (val) {744 //组装JSON745 var smallAchorInfo = {746 input_stream_id: val.streamID,747 layout_params: {748 image_layer: layerIndex + 2,749 image_width: smallAnchorWidth,750 image_height: smallAnchorHeight,751 location_x: subLocationX,752 location_y: subLocationY - layerIndex * smallAnchorHeight753 }754 }755 streamInfoArray.push(smallAchorInfo);756 layerIndex++;757 });758 }759 } else {760 var bigAnchorInfo = {761 input_stream_id: bigAnchorStreamID || '',762 layout_params: {763 image_layer: 1764 }765 }766 streamInfoArray.push(bigAnchorInfo);767 }768 var para = {769 app_id: accountInfo.sdkAppID.toString(),770 interface: 'mix_streamv2.start_mix_stream_advanced',771 mix_stream_session_id: bigAnchorStreamID,772 output_stream_id: bigAnchorStreamID,773 input_stream_list: streamInfoArray774 }775 var interfaceObj = {776 interfaceName: 'Mix_StreamV2',777 para: para778 }779 var reqParam = {780 timestamp: Math.round((Date.now() / 1000)),781 eventId: Math.round((Date.now() / 1000)),782 interface: interfaceObj783 }784 return reqParam;785}786function setVideoRatio(ratio) {787 if (ratio == 1) {788 //9:16789 bigAnchorWidth = 360;790 bigAnchorHeight = 640;791 } else {792 //3:4793 bigAnchorWidth = 480;794 bigAnchorHeight = 640;795 }796}797function sendC2CCustomMsg(object) {798 var body = {799 cmd: object.cmd,800 data: {801 userID: accountInfo.userID,802 userName: accountInfo.userName,803 userAvatar: accountInfo.userAvatar,804 msg: object.msg || ''805 }806 }807 var msg = {808 data: JSON.stringify(body)809 }810 webimhandler.sendC2CCustomMsg(object.toUserID?object.toUserID:roomInfo.roomCreator, msg, function (ret) {811 if (ret && ret.errCode) {812 console.log('请求连麦失败:', JSON.stringify(ret));813 object.fail && object.fail(ret);814 return;815 }816 object.success && object.success({});817 });818}819/**820 * 对外暴露函数821 * @type {Object}822 */823module.exports = {824 exitRoom: exitRoom, // 退出房间825 sendRoomTextMsg: sendRoomTextMsg, // 发送文本消息826 setListener: setListener, // 设置监听事件827 joinAnchor: joinAnchor, //加入连麦828 quitJoinAnchor: quitJoinAnchor, //退出连麦829 requestJoinAnchor: requestJoinAnchor,830 acceptJoinAnchor: acceptJoinAnchor,831 rejectJoinAnchor: rejectJoinAnchor,832 kickoutJoinAnchor: kickoutJoinAnchor,833 getAccountInfo: getAccountInfo,834 setVideoRatio: setVideoRatio,835 sendC2CCustomMsg: sendC2CCustomMsg,836 getAnchors: getAnchors...

Full Screen

Full Screen

streamUtils-test.js

Source:streamUtils-test.js Github

copy

Full Screen

...135 source.push("andré");136 source.push("bruno");137 source.push("robert");138 source.push(null);139 mergeStreams(source)140 .pipe(transformObject(data => data.substring(0, 1)))141 .pipe(writeObject(data => chunks.push(data)))142 .on("finish", () => {143 assert.deepStrictEqual(chunks, ["a", "b", "r"]);144 done();145 });146 });147 it("can mergeStreams streams (error propagation)", done => {148 let source = createStream();149 source.push("andré");150 mergeStreams(151 source,152 writeObject(() => ({}))153 )154 .on("error", e => {155 assert.strictEqual(e, "Error from source");156 done();157 })158 .on("finish", () => {159 assert.fail();160 done();161 });162 source.emit("error", "Error from source");163 });164 it("can mergeStreams streams (error propagation with promise)", done => {165 let source = createStream();166 mergeStreams(167 source,168 writeObject(() => ({}))169 )170 .then(() => {171 assert.fail();172 done();173 })174 .catch(e => {175 assert.strictEqual(e, "emitted");176 done();177 });178 source.emit("error", "emitted");179 });180 it("can mergeStreams streams (error propagation from a nested stream)", done => {181 let source = createStream();182 source.push("first");183 mergeStreams(184 source,185 writeObject(() => {186 throw new Error("write");187 })188 )189 .on("error", e => {190 assert.strictEqual(e.message, "write");191 done();192 })193 .on("finish", () => {194 assert.fail();195 done();196 });197 });198 it("can pipeline streams", async () => {199 let chunks = [];200 let source = createStream();201 source.push("andré");202 source.push("bruno");203 source.push("robert");204 source.push(null);205 await pipeline(206 source,207 transformObject(data => data.substring(0, 1)),208 writeObject(data => chunks.push(data))209 );210 assert.deepStrictEqual(chunks, ["a", "b", "r"]);211 });212 it("can pipeline streams (error propagation)", done => {213 let source = createStream();214 pipeline(215 source,216 writeObject(() => ({}))217 )218 .then(() => {219 assert.fail();220 done();221 })222 .catch(e => {223 assert.strictEqual(e, "emitted");224 done();225 });226 source.push("first");227 source.emit("error", "emitted");228 });229 it("can pipeline streams (error callback propagation)", async () => {230 let source = createStream();231 let promise = pipeline(232 source,233 writeObject(() => {234 throw new Error("An error occurred");235 })236 );237 try {238 source.push("andré");239 await promise;240 assert.fail();241 } catch (e) {242 assert.strictEqual(e.message, "An error occurred");243 }244 });245 it("can use pipeline with mergeStreamsd streams", async () => {246 let source = createStream();247 let multi = mergeStreams(248 source,249 transformObject(d => d)250 );251 source.push("first");252 source.push(null);253 await pipeline(254 multi,255 writeObject(() => ({}))256 );257 });258 it("should ignoreEmpty", done => {259 let chunks = [];260 let stream = createStream();261 stream.push("first");...

Full Screen

Full Screen

prepare-dependencies.js

Source:prepare-dependencies.js Github

copy

Full Screen

...21 notesHtml = gulp.src(baseRevealJSPath + '/plugin/notes/notes.html')22 .pipe(gulp.dest(revealJsDestDir + '/plugin/notes/')),23 zoomJs = gulp.src(baseRevealJSPath + '/plugin/zoom-js/zoom.js')24 .pipe(gulp.dest(revealJsDestDir + '/plugin/zoom-js/'));25 return plugins.mergeStreams(26 mainRevealCss,27 paperCSS,28 mainRevealJs,29 zenBurnCss,30 notesJs,31 notesHtml,32 zoomJs,33 markedJs,34 resetCss35 );36 });37 ////////////////////////////// Managing highlightJS and dependencies38 // We copy in revealjs, because we cannot set it up on revealjs39 // so.. reusing. cf. https://github.com/hakimel/reveal.js/#dependencies40 /////////////////41 gulp.task('prepare:highlightjs', function () {42 var highlightNodeModule = current_config.nodeModulesDir + '/highlight.js',43 highlightDestDir = current_config.distDir + '/reveal.js/plugin/highlight',44 highlightjsStyleRename = gulp.src(highlightNodeModule + '/styles/*.css')45 .pipe(plugins.rename(function (path) {46 // Removing the ".min" part of the name to avoid revealjs messing up47 path.basename += ".min";48 }))49 .pipe(gulp.dest(highlightDestDir + '/styles/')),50 highlightScript = gulp.src(highlightNodeModule + '/lib/highlight.js')51 .pipe(gulp.dest(highlightDestDir));52 return plugins.mergeStreams(highlightjsStyleRename, highlightScript);53 });54 ////////////////////////////// Managing fontawesome and dependencies55 gulp.task('prepare:fontawesome', function () {56 var fontAwesomeCss = gulp.src(current_config.nodeModulesDir + '/font-awesome/css/**/*')57 .pipe(gulp.dest(current_config.distDir + '/styles/'));58 var fontAwesomeFonts = gulp.src(current_config.nodeModulesDir + '/font-awesome/fonts/**/*')59 .pipe(gulp.dest(current_config.distDir + '/fonts/'));60 return plugins.mergeStreams(fontAwesomeCss, fontAwesomeFonts);61 });62 ////////////////////////////// Managing RevelaJS Menu Plugin and dependencies63 gulp.task('prepare:revealjs-plugins', function () {64 var revealPluginMenu = gulp.src(current_config.nodeModulesDir + '/reveal.js-menu/**/*')65 .pipe(gulp.dest(current_config.distDir + '/reveal.js/plugin/reveal.js-menu/'));66 var revealPluginToolbar = gulp.src(current_config.nodeModulesDir + '/reveal.js-toolbar/**/*')67 .pipe(gulp.dest(current_config.distDir + '/reveal.js/plugin/reveal.js-toolbar/'));68 var revealPluginCopyCode = gulp.src(current_config.scriptsSrcPath + '/*.js')69 .pipe(gulp.dest(current_config.distDir + '/reveal.js/plugin/reveal.js-copycode/'));70 return plugins.mergeStreams(revealPluginMenu, revealPluginToolbar, revealPluginCopyCode);71 });...

Full Screen

Full Screen

gulpfile.js

Source:gulpfile.js Github

copy

Full Screen

...40};41async function compileJS(){42 return new Promise(async resolve => {43 await fs.ensureDir(compiledJS);44 mergeStreams(45 ...Object.keys(assets.js).map(file => {46 return gulp.src(assets.js[file])47 .pipe(terser())48 .pipe(concat(file + '.js'))49 .pipe(gulp.dest(compiledJS))50 })51 ).on('finish', () => resolve())52 });53}54async function compileCSS(){55 return new Promise(async resolve => {56 await fs.ensureDir(compiledCSS);57 mergeStreams(58 ...Object.keys(assets.css).map(file => {59 return gulp.src(assets.css[file])60 .pipe(cleanCSS())61 .pipe(concat(file + '.css'))62 .pipe(gulp.dest(compiledCSS))63 })64 ).on('finish', () => resolve())65 });66}67async function renderTemplates() {68 return gulp.src('templates/pages/**/*.html')69 .pipe(nunjucksRender({70 path: ['templates', 'templates/partials', 'templates/pages'],71 data: {...

Full Screen

Full Screen

mergeStreams-test.js

Source:mergeStreams-test.js Github

copy

Full Screen

...5 it("can merge multiple streams", (done) => {6 let result = "";7 let source1 = createStream(["andré"]);8 let source2 = createStream(["bruno"]);9 mergeStreams(source1, source2)10 .pipe(writeData((data) => (result += data)))11 .on("finish", () => {12 assert.deepStrictEqual(result, "andrébruno");13 done();14 });15 });16 it("can merge multiple streams (factory)", (done) => {17 let result = "";18 mergeStreams(19 () => createStream(["andré"]),20 () => createStream(["bruno"])21 )22 .pipe(writeData((data) => (result += data)))23 .on("finish", () => {24 assert.deepStrictEqual(result, "andrébruno");25 done();26 });27 });28 it("can merge multiple streams (async factory)", (done) => {29 let result = "";30 mergeStreams(31 () => Promise.resolve(createStream(["andré"])),32 () => Promise.resolve(createStream(["bruno"]))33 )34 .pipe(writeData((data) => (result += data)))35 .on("finish", () => {36 assert.deepStrictEqual(result, "andrébruno");37 done();38 });39 });40 it("can merge multiple streams (sequentially)", (done) => {41 let result = "";42 let source1 = createStream(["andré"]);43 let source2 = createStream(["bruno"]);44 mergeStreams(source1, source2, { sequential: true })45 .pipe(writeData((data) => (result += data)))46 .on("finish", () => {47 assert.deepStrictEqual(result, "andrébruno");48 done();49 });50 });51 it("can merge multiple streams (sequentially+factory)", (done) => {52 let result = "";53 mergeStreams(54 () => createStream(["andré"]),55 () => createStream(["bruno"]),56 { sequential: true }57 )58 .pipe(writeData((data) => (result += data)))59 .on("finish", () => {60 assert.deepStrictEqual(result, "andrébruno");61 done();62 });63 });64 it("can iterate over a merged stream", async () => {65 let source1 = createStream(["andré"]);66 let source2 = createStream(["bruno"]);67 let chunks = [];68 for await (const chunk of mergeStreams(source1, source2)) {69 chunks.push(chunk);70 }71 assert.deepStrictEqual(chunks, ["andré", "bruno"]);72 });...

Full Screen

Full Screen

migrations.js

Source:migrations.js Github

copy

Full Screen

...12 Meteor.users.update(user, { $set: { "profile.streams":streamsIds } });13 });14 Streams.remove(streamFrom);15 }16 mergeStreams("SbCvHpNynrcSwd9HY", "CXWYcdwNhBEGyuLzD"); // 2-ой с 6-ым17 mergeStreams("fwPYXXKAB2Ftpz2sM", "FmGsF8534WwGHNoXB"); // 3-ий с 7-ым18 mergeStreams("fwPYXXKAB2Ftpz2sM", "9L5MS5wAwQtGrbfAW"); // 3-ий с 8-ым19 mergeStreams("5M6rnhF5EGed3qiLD", "LJASwBsDcE8n7SwnC"); // 4-ый с 1-ым20 Meteor.users.update({ "profile.streams": "ZvYrFciXzsD8NQJHB" }, { $set: { "profile.mentor": "znksXwGwk5NdLGA7o" } }, { multi: 1 }); // 1-ый - Елена Морозова21 Meteor.users.update({ "profile.streams": "SbCvHpNynrcSwd9HY" }, { $set: { "profile.mentor": "tPSxNPMrj99tBwcMu" } }, { multi: 1 }); // 2-ый - Мария Фалалеева22 Meteor.users.update({ "profile.streams": "fwPYXXKAB2Ftpz2sM" }, { $set: { "profile.mentor": "n9QshxZoSGWL6zPC2" } }, { multi: 1 }); // 3-ый - Юля Аделова23 Meteor.users.update({ "profile.streams": "5M6rnhF5EGed3qiLD" }, { $set: { "profile.mentor": "puxdzvQJrxJE96wFb" } }, { multi: 1 }); // 4-ый - Анна Соколова24};*/25export default function () {26 // 01.06.14 merge streams27 /*Migrations.add({28 version: 10614,29 name: 'merge streams',30 up: migrateAt1061431 });*/...

Full Screen

Full Screen

streams.js

Source:streams.js Github

copy

Full Screen

1const datetime = require('./datetime');2/* eslint-disable no-console */3const sortFunc = (a,b) => {4 return a.timestamp.diff(b.timestamp);5};6const mergeStreams = (...args) => {7 if (args.length === 1) {8 return args[0];9 }10 let ret = args[0].slice(0);11 for (let i=1, len=args.length; i < len; i++) {12 ret = ret.concat(args[i]);13 }14 ret = ret.sort(sortFunc);15 return ret.filter((item, i, self) => {16 return !(self[i+1] && item.id === self[i+1].id);17 });18};19const normalize = (stream) => {20 for (let i=0, len=stream.length; i < len; i++) {21 stream[i].timestamp = datetime.create(stream[i].timestamp);22 }23 return stream;24};25module.exports = {26 merge: mergeStreams,27 normalize: normalize28};...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/*2 * @license MIT http://www.opensource.org/licenses/mit-license.php3 * @author Hovhannes Babayan <bhovhannes at gmail dot com>4 */5const { mergeFiles } = require("./src/mergeFiles.js");6const { mergeStreams } = require("./src/mergeStreams.js");7const { mergeToString } = require("./src/mergeToString.js");8module.exports = {9 mergeFiles,10 mergeStreams,11 mergeToString,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const stream1 = fs.createReadStream('test1.mp4');3const stream2 = fs.createReadStream('test2.mp4');4const stream3 = fs.createReadStream('test3.mp4');5const mergedStream = mergeStreams([stream1, stream2, stream3]);6const fileWriteStream = fs.createWriteStream('mergedVideo.mp4');7mergedStream.pipe(fileWriteStream);8The first approach I tried was to use the page.evaluate() method to execute the following script:9window.speechSynthesis.speak(new SpeechSynthesisUtterance('hello'));10The second approach I tried was to use the page.evaluateOnNewDocument() method to execute the following script:11window.speechSynthesis = {12 speak: () => {}13};14The third approach I tried was to use the page.evaluateOnNewDocument() method to

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const stream1 = fs.createReadStream('test1.mp4');8 const stream2 = fs.createReadStream('test2.mp4');9 await page.evaluate(async ({stream1, stream2}) => {10 const { mergeStreams } = window['playwright'].internal;11 const mergedStream = await mergeStreams([stream1, stream2]);12 const video = document.createElement('video');13 video.src = URL.createObjectURL(mergedStream);14 video.controls = true;15 document.body.appendChild(video);16 }, {stream1, stream2});17})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright/lib/server/browserType');2(async () => {3 const stream1 = fs.createReadStream('test1.mp4');4 const stream2 = fs.createReadStream('test2.mp4');5 const streams = await mergeStreams([stream1, stream2], { duration: 10 });6 const writeStream = fs.createWriteStream('test.mp4');7 streams.pipe(writeStream);8})();9const { mergeVideo } = require('playwright/lib/server/browserType');10(async () => {11 await mergeVideo(['test1.mp4', 'test2.mp4'], 'test.mp4', { duration: 10 });12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright/lib/server/chromium/crVideo');2const video1 = fs.createReadStream('video1.webm');3const video2 = fs.createReadStream('video2.webm');4const mergedVideo = mergeStreams([video1, video2]);5mergedVideo.pipe(fs.createWriteStream('mergedVideo.webm'));6const { mergeVideos } = require('playwright/lib/server/chromium/crVideo');7await mergeVideos(['video1.webm', 'video2.webm'], 'mergedVideo.webm');8await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright-core/lib/utils/mergeStreams');2const { createWriteStream } = require('fs');3const { createReadStream } = require('fs');4const path = require('path');5const { mkdirSync } = require('fs');6const { existsSync } = require('fs');7const playwright = require('playwright-core');8const puppeteer = require('puppeteer');9const ffmpeg = require('fluent-ffmpeg');10const ffmpeg_static = require('ffmpeg-static');11const fluent_ffmpeg = require('fluent-ffmpeg');12const fluent_ffmpeg_static = require('fluent-ffmpeg-static');13const fluent_ffmpeg_binaries = require('fluent-ffmpeg-binaries');14const fluent_ffmpeg_binaries_3_3_3 = require('fluent-ffmpeg-binaries-3.3.3');15const fluent_ffmpeg_binaries_4_0_2 = require('fluent-ffmpeg-binaries-4.0.2');16const fluent_ffmpeg_binaries_4_1_3 = require('fluent-ffmpeg-binaries-4.1.3');17const fluent_ffmpeg_binaries_4_2_2 = require('fluent-ffmpeg-binaries-4.2.2');18const fluent_ffmpeg_binaries_4_2_4 = require('fluent-ffmpeg-binaries-4.2.4');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright/lib/utils/streams');2mergeStreams(stream1, stream2, stream3);3const { mergeStreams } = require('playwright/lib/utils/streams');4mergeStreams(stream1, stream2, stream3);5const { mergeStreams } = require('playwright/lib/utils/streams');6mergeStreams(stream1, stream2, stream3);7const { mergeStreams } = require('playwright/lib/utils/streams');8mergeStreams(stream1, stream2, stream3);9const { mergeStreams } = require('playwright/lib/utils/streams');10mergeStreams(stream1, stream2, stream3);11const { mergeStreams } = require('playwright/lib/utils/streams');12mergeStreams(stream1, stream2, stream3);13const { mergeStreams } = require('playwright/lib/utils/streams');14mergeStreams(stream1, stream2, stream3);15const { mergeStreams } = require('playwright/lib/utils/streams');16mergeStreams(stream1, stream2, stream3);17const { mergeStreams } = require('playwright/lib/utils/streams');18mergeStreams(stream1, stream2, stream3);19const { mergeStreams } = require('playwright/lib/utils/streams');20mergeStreams(stream1, stream2, stream3);21const { mergeStreams } = require('playwright/lib/utils/streams');22mergeStreams(stream1, stream2, stream3);23const { mergeStreams } = require('playwright/lib/utils/streams');24mergeStreams(stream1, stream2, stream3);25const { mergeStreams } = require('playwright/lib/utils/streams');26mergeStreams(stream1, stream2, stream3);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('playwright-core/lib/server/supplements/recorder/recorderApp');2const { Readable } = require('stream');3const { createWriteStream } = require('fs');4const readableStream1 = Readable.from(['1', '2', '3', '4', '5']);5const readableStream2 = Readable.from(['6', '7', '8', '9', '10']);6const mergedStream = mergeStreams([readableStream1, readableStream2]);7const writeStream = createWriteStream('merged.txt');8mergedStream.pipe(writeStream);9mergedStream.on('end', () => {10 writeStream.close();11});12const { mergeStreams } = require('playwright-core/lib/server/supplements/recorder/recorderApp');13const { Readable } = require('stream');14const { createWriteStream } = require('fs');15const readableStream1 = Readable.from(['1', '2', '3', '4', '5']);16const readableStream2 = Readable.from(['6', '7', '8', '9', '10']);17const mergedStream = mergeStreams([readableStream1, readableStream2]);18const writeStream = createWriteStream('merged.txt');19mergedStream.pipe(writeStream);20mergedStream.on('end', () => {21 writeStream.close();22});23const { mergeStreams } = require('playwright-core/lib/server/supplements/recorder/recorderApp');24const { Readable } = require('stream');25const { createWriteStream } = require('fs');26const readableStream1 = Readable.from(['1', '2', '3', '4', '5']);27const readableStream2 = Readable.from(['6',

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mergeStreams } = require('@playwright/test/lib/utils/mergeStreams');2const { createReadStream } = require('fs');3const { createWriteStream } = require('fs');4const readStream1 = createReadStream('file1.txt');5const readStream2 = createReadStream('file2.txt');6const writeStream = createWriteStream('merged.txt');7mergeStreams([readStream1, readStream2], writeStream);8writeStream.write('data to be written');9writeStream.end();10readStream1.close();11readStream2.close();12const readStream3 = createReadStream('merged.txt');13readStream3.on('data', (chunk) => {14 console.log(chunk.toString());15});16readStream3.close();17const fs = require('fs');18fs.unlinkSync('merged.txt');19fs.unlinkSync('file1.txt');20fs.unlinkSync('file2.txt');21fs.unlinkSync('merged.txt');22fs.writeFileSync('file1.txt', 'data in file1');23fs.writeFileSync('file2.txt', 'data in file2');24fs.writeFileSync('merged.txt', 'data in merged file');25fs.unlinkSync('file1.txt');26fs.unlinkSync('file2.txt');27fs.unlinkSync('merged.txt');28fs.writeFileSync('file1.txt', 'data in file1');29fs.writeFileSync('file2.txt', 'data in file2');30fs.writeFileSync('merged.txt', 'data in merged file');31fs.unlinkSync('file1.txt');32fs.unlinkSync('file2.txt');33fs.unlinkSync('merged.txt');34fs.writeFileSync('file1.txt', 'data in file1');35fs.writeFileSync('file2.txt', 'data in file2');36fs.writeFileSync('merged.txt', 'data in merged file');

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful