How to use recorder method in differencify

Best JavaScript code snippet using differencify

video_recorder.js

Source:video_recorder.js Github

copy

Full Screen

1;(function(){2if(window.BX.VideoRecorder)3 return;4/**5 * Object to record video messages.6 * order inside:7 * start()8 * show permission popup9 * askDevicePermission(), showLayout() render popup on full screen10 * askDevicePermission() set stream to <video>11 * <video> after first playing invoke beforeRecord()12 * beforeRecord() attach analyzer and launches startTimer13 * startRecord() launches record until stop button used.14* */15BX.VideoRecorder = {16 popupPermissionsShown: false,17 popupConfirm: null,18 constraints: {audio: {}, video: {width: 1280, height: 720, facingMode: "user"}},19 analyserNode: null,20 activeFormID: null,21 chunks: [],22 bindedForms: [],23 recorderInterval: 5000,24 transformLimit: 0,25 transformTime: 70,26 transformTimerShown: false,27 errorCode: null,28 getScreenWidth: function()29 {30 if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement)31 {32 return document.body.clientWidth;33 }34 else35 {36 return window.screen.width;37 }38 },39 getScreenHeight: function()40 {41 return document.documentElement.clientHeight;42 },43 isPermissionsAsked: function()44 {45 return BX.VideoRecorder.popupPermissionsShown;46 },47 isAvailable: function(report)48 {49 report = report === true;50 var error = BX.VideoRecorder.error = null;51 if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || typeof MediaRecorder === 'undefined')52 {53 error = 'Not available or old browser';54 BX.VideoRecorder.errorCode = 'BLOG_VIDEO_RECORD_REQUIREMENTS';55 }56 else if (BX.browser.IsChrome() && location.protocol !== 'https:')57 {58 error = 'In chrome works on https only';59 BX.VideoRecorder.errorCode = 'BLOG_VIDEO_RECORD_ERROR_CHROME_HTTPS';60 }61 else if (BX.browser.IsIE())62 {63 error = 'Not available in IE';64 BX.VideoRecorder.errorCode = 'BLOG_VIDEO_RECORD_REQUIREMENTS';65 }66 if(error)67 {68 if(report)69 {70 console.log(error);71 }72 return false;73 }74 return true;75 },76 bindEvents: function(handler)77 {78 if(!BX.VideoRecorder.isAvailable())79 {80 return;81 }82 if(BX.VideoRecorder.bindedForms.indexOf(handler.params.formID) !== -1)83 {84 return;85 }86 BX.VideoRecorder.bindedForms.push(handler.params.formID);87 BX.addCustomEvent(handler.eventNode, 'onFileIsAdded', function(file, controller, obj, blob) {88 setTimeout(function() {89 if (blob["hasTobeInserted"] === true)90 controller.insertFile(file.id);91 }, 1000);92 });93 BX.addCustomEvent(window, 'onAddVideoMessage', function(file, formID)94 {95 if(!formID)96 {97 return;98 }99 for(var i in handler.controllers)100 {101 if (handler.controllers.hasOwnProperty(i) &&102 handler.controllers[i]["storage"] === "disk" &&103 formID === handler.params.formID)104 {105 handler.controllers[i].handler.agent.onChange([file]);106 break;107 }108 }109 });110 },111 showLayout: function()112 {113 BX.VideoRecorder.lockScroll();114 BX.VideoRecorder.recordCount = 0;115 BX.VideoRecorder.startCount = 5;116 BX.VideoRecorder.state = 'idle';117 BX.VideoRecorder.transformTimeLeft = BX.VideoRecorder.transformTime;118 BX.VideoRecorder.transformTimerShown = false;119 clearInterval(BX.VideoRecorder.recordInterval);120 BX.VideoRecorder.layout = BX.create('div', {props: {className: 'bx-videomessage-video-wrapper'}, children: [121 BX.create('div', {props: {className: 'bx-videomessage-video-close'}, events: {122 click: function()123 {124 BX.VideoRecorder.hideLayout();125 }126 }}),127 BX.VideoRecorder.videoOverlay = BX.create('div', {props: {className: 'bx-videomessage-video-overlay'}, style: {height: BX.VideoRecorder.getScreenHeight() + 'px'}, children: [128 BX.VideoRecorder.startTimer = BX.create('div', {props: {className: 'bx-videomessage-video-starttimer'}, text: '5'})129 ]}),130 BX.VideoRecorder.videoContainer = BX.create('div', {props: {className: 'bx-videomessage-video-container'}, style: {height: BX.VideoRecorder.getScreenHeight() + 'px'}, children: [131 BX.VideoRecorder.videoWrap = BX.create('div', {props: {className: 'bx-videomessage-video-wrap'}, style: {height: BX.VideoRecorder.getScreenHeight() + 'px'}, children: [132 BX.VideoRecorder.waterMark = BX.create('div', {133 props: {className: 'bx-videomessage-watermark'},134 style: {display: 'none'},135 html: BX.message('BLOG_VIDEO_RECORD_LOGO')136 }),137 BX.VideoRecorder.transformTimeContainer = BX.create('div', {props: {className: 'bx-videomessage-transform-time-container'}, children: [138 BX.create('span', {props: {className: 'bx-videomessage-transform-time-close'}, html: '', events: {click: BX.VideoRecorder.hideTransformTimer}}),139 BX.create('span', {props: {className: 'bx-videomessage-transform-time-text'}, html: BX.message('BLOG_VIDEO_RECORD_TRANFORM_LIMIT_TEXT')})140 ]}),141 BX.VideoRecorder.outputVideo = BX.create('video', {props: {className: 'bx-videomessage-video', width: BX.VideoRecorder.getScreenWidth(), loop: false}, events: {142 'playing': function()143 {144 if(BX.VideoRecorder.state === 'idle')145 {146 BX.VideoRecorder.resize();147 BX.VideoRecorder.beforeRecord();148 }149 },150 'ended': function()151 {152 BX.VideoRecorder.state = 'idle';153 BX.VideoRecorder.buttonStop.style.display = 'none';154 BX.VideoRecorder.buttonPlay.style.display = 'block';155 }156 }}),157 BX.VideoRecorder.buttonPlay = BX.create('span', {props: {className: 'bx-videomessage-playbutton'}, events: {158 'click': function()159 {160 if(BX.VideoRecorder.state === 'idle')161 {162 BX.VideoRecorder.outputVideo.play();163 BX.VideoRecorder.outputVideo.volume = 1;164 BX.VideoRecorder.state = 'playing';165 BX.VideoRecorder.buttonStop.style.display = 'inline-block';166 BX.VideoRecorder.buttonPlay.style.display = 'none';167 }168 }169 }}),170 BX.VideoRecorder.panel = BX.create('div', {props: {className: 'bx-videomessage-panel'}, style: {display: 'none'}, children: [171 BX.VideoRecorder.recordTimer = BX.create('span', {props: {className: 'bx-videomessage-video-timer'}, text: '00:00'}),172 BX.VideoRecorder.buttonStop = BX.create('span', {props: {className: 'webform-button webform-button-blue webform-button-rounded'}, text: BX.message('BLOG_VIDEO_RECORD_STOP_BUTTON'), events: {173 'click': function(e)174 {175 if(BX.VideoRecorder.state === 'recording')176 {177 BX.VideoRecorder.state = 'idle';178 BX.VideoRecorder.recorder.stop();179 BX.hide(BX.VideoRecorder.recordMark);180 BX.hide(BX.VideoRecorder.analyzerElement);181 clearInterval(BX.VideoRecorder.recordInterval);182 BX.VideoRecorder.buttonPlay.style.display = 'block';183 BX.VideoRecorder.buttonStop.style.display = 'none';184 return false;185 }186 else if(BX.VideoRecorder.state === 'playing')187 {188 BX.VideoRecorder.outputVideo.pause();189 BX.VideoRecorder.state = 'idle';190 BX.VideoRecorder.buttonStop.style.display = 'none';191 BX.VideoRecorder.buttonPlay.style.display = 'block';192 }193 }194 }}),195 BX.VideoRecorder.buttonSave = BX.create('span', {props: {className: 'webform-button webform-button-accept webform-button-rounded webform-button-text-white'}, style:{display: 'none'}, text: BX.message('BLOG_VIDEO_RECORD_USE_BUTTON'), events: {196 'click': function()197 {198 if(BX.VideoRecorder.activeFormID)199 {200 BX.fireEvent(BX('bx-b-uploadfile-' + BX.VideoRecorder.activeFormID), 'click');201 var file = new File(BX.VideoRecorder.chunks, 'videomessage-' + BX.date.format(BX.date.convertBitrixFormat(BX.message("FORMAT_DATETIME"))) + '.webm');202 file.hasTobeInserted = true;203 BX.onCustomEvent(window, 'onAddVideoMessage', [file, BX.VideoRecorder.activeFormID]);204 BX.VideoRecorder.hideLayout();205 }206 }207 }}),208 BX.VideoRecorder.buttonCancel = BX.create('span', {props: {className: 'webform-button-link bx-videomessage-video-button-cancel'}, text: BX.message('BLOG_VIDEO_RECORD_CANCEL_BUTTON'), events: {209 'click': function()210 {211 BX.VideoRecorder.hideLayout();212 }213 }}),214 BX.VideoRecorder.buttonRestart = BX.create('span', {props: {className: 'webform-button webform-button-blue webform-button-rounded'}, style:{display: 'none'}, text: BX.message('BLOG_VIDEO_RECORD_RESTART_BUTTON'), events: {215 'click': function()216 {217 BX.VideoRecorder.restartRecord();218 }219 }}),220 BX.VideoRecorder.recordMark = BX.create('div',221 {222 props: {className: 'bx-videomessage-record'},223 style: {display: 'none'},224 html: '<span class="bx-videomessage-record-inner">' + BX.message('BLOG_VIDEO_RECORD_IN_PROGRESS_LABEL') + '</span>'225 }),226 BX.VideoRecorder.analyzerElement = BX.create('canvas', {props: {className: 'bx-videomessage-analyzer'}})227 ]})228 ]})229 ]})230 ]});231 BX.VideoRecorder.popupRecord = new BX.PopupWindow('bx-popup-videomessage-record', null, {232 zIndex: 300,233 autoHide: false,234 closeByEsc: false,235 overlay : true,236 events : { onPopupClose : function() { this.destroy() }, onPopupDestroy : function() { BX.VideoRecorder.popupRecord = null }},237 content : BX.VideoRecorder.layout,238 height: BX.VideoRecorder.getScreenHeight(),239 width: BX.VideoRecorder.getScreenWidth(),240 noAllPaddings: true241 });242 BX.VideoRecorder.popupRecord.show();243 BX.VideoRecorder.popupRecord.enterFullScreen();244 BX.VideoRecorder.outputVideo.volume = 0;245 BX.VideoRecorder.canvasContext = BX.VideoRecorder.analyzerElement.getContext('2d');246 BX.VideoRecorder.canvasContext.imageSmoothingEnabled = false;247 BX.VideoRecorder.canvasContext.webkitImageSmoothingEnabled = false;248 },249 beforeRecord: function()250 {251 window.addEventListener('resize', BX.VideoRecorder.resize);252 BX.VideoRecorder.startCount = 5;253 BX.addClass(BX.VideoRecorder.startTimer, 'started');254 BX.VideoRecorder.attachAnalyzer();255 BX.VideoRecorder.renderAnalyzer();256 BX.show(BX.VideoRecorder.analyzerElement, 'inline-block');257 var nextSecond = function()258 {259 clearTimeout(BX.VideoRecorder.startTimeout);260 BX.VideoRecorder.startTimer.innerText = BX.VideoRecorder.startCount;261 BX.VideoRecorder.startTimeout = setTimeout(function()262 {263 BX.VideoRecorder.startCount = BX.VideoRecorder.startCount - 1;264 if(BX.VideoRecorder.startCount === 0)265 {266 BX.removeClass(BX.VideoRecorder.startTimer, 'started');267 BX.VideoRecorder.startRecord();268 }269 else270 {271 nextSecond();272 }273 }, 1000);274 };275 nextSecond();276 },277 startRecord: function()278 {279 BX.VideoRecorder.chunks = [];280 BX.VideoRecorder.videoOverlay.style.display = 'none';281 var recordOptions = {mimeType: 'video/webm;codecs=vp8'};282 if(!MediaRecorder.isTypeSupported(recordOptions.mimeType))283 {284 recordOptions = {mimeType: 'video/webm;codecs=vp9'};285 if(!MediaRecorder.isTypeSupported(recordOptions.mimeType))286 {287 recordOptions = {mimeType: 'video/webm'};288 }289 }290 try {291 BX.VideoRecorder.recorder = new MediaRecorder(BX.VideoRecorder.stream, recordOptions);292 }293 catch(e)294 {295 BX.VideoRecorder.showMessage(296 BX.message('BLOG_VIDEO_RECORD_REQUIREMENTS'),297 [],298 BX.message('BLOG_VIDEO_RECORD_REQUIREMENTS_TITLE')299 );300 BX.VideoRecorder.hideLayout();301 return;302 }303 BX.VideoRecorder.recorder.start(BX.VideoRecorder.recorderInterval);304 BX.VideoRecorder.recordSize = 0;305 BX.VideoRecorder.recordLength = 0;306 BX.VideoRecorder.recorder.ondataavailable = function(e)307 {308 BX.VideoRecorder.recordSize += e.data.size;309 BX.VideoRecorder.recordLength += BX.VideoRecorder.recorderInterval / 1000;310 BX.VideoRecorder.chunks.push(e.data);311 if(BX.VideoRecorder.isTimeToShowTransformationAlert())312 {313 BX.VideoRecorder.startTransformationCounter();314 }315 };316 BX.VideoRecorder.recorder.onstop = function()317 {318 BX.VideoRecorder.hideTransformTimer();319 BX.VideoRecorder.recordBlob = new Blob(BX.VideoRecorder.chunks, {'type': 'video/webm'});320 BX.VideoRecorder.outputVideo.src = URL.createObjectURL(BX.VideoRecorder.recordBlob);321 BX.VideoRecorder.state = 'idle';322 BX.VideoRecorder.buttonPlay.style.display = 'block';323 BX.VideoRecorder.buttonSave.style.display = 'inline-block';324 BX.VideoRecorder.buttonCancel.style.display = 'inline-block';325 BX.VideoRecorder.buttonRestart.style.display = 'inline-block';326 };327 BX.VideoRecorder.setVideoSrc(BX.VideoRecorder.stream);328 BX.VideoRecorder.outputVideo.volume = 0;329 BX.VideoRecorder.outputVideo.play();330 BX.VideoRecorder.state = 'recording';331 BX.show(BX.VideoRecorder.recordMark, 'inline-block');332 BX.VideoRecorder.recordInterval = setInterval(function()333 {334 BX.VideoRecorder.recordCount++;335 BX.VideoRecorder.recordTimer.innerText = BX.VideoRecorder.getTimeString(BX.VideoRecorder.recordCount);336 }, 1000);337 },338 attachAnalyzer: function()339 {340 BX.VideoRecorder.audioContext = new (window.AudioContext || window.webkitAudioContext);341 BX.VideoRecorder.analyserNode = BX.VideoRecorder.audioContext.createAnalyser();342 BX.VideoRecorder.analyserNode.fftSize = 128;343 BX.VideoRecorder.analyserNode.minDecibels = -80;344 BX.VideoRecorder.analyserNode.maxDecibels = -10;345 BX.VideoRecorder.mediaStreamNode = BX.VideoRecorder.audioContext.createMediaStreamSource(BX.VideoRecorder.stream);346 BX.VideoRecorder.mediaStreamNode.connect(BX.VideoRecorder.analyserNode);347 BX.VideoRecorder.frequencyData = new Uint8Array(BX.VideoRecorder.analyserNode.frequencyBinCount);348 BX.VideoRecorder.lastFrameDate = (new Date()).getTime();349 },350 renderAnalyzer: function()351 {352 if(!BX.VideoRecorder.analyzerElement)353 {354 return;355 }356 window.requestAnimationFrame(BX.VideoRecorder.renderAnalyzer.bind(BX.VideoRecorder));357 var now = (new Date()).getTime();358 if(now - BX.VideoRecorder.lastFrameDate < 50)359 {360 return;361 }362 BX.VideoRecorder.lastFrameDate = now;363 BX.VideoRecorder.analyserNode.getByteFrequencyData(BX.VideoRecorder.frequencyData);364 var width = BX.VideoRecorder.analyzerElement.width;365 var height = BX.VideoRecorder.analyzerElement.height;366 var frequencyPoints = BX.VideoRecorder.analyserNode.frequencyBinCount;367 BX.VideoRecorder.canvasContext.clearRect(0, 0, width, height);368 BX.VideoRecorder.canvasContext.beginPath();369 var barWidth = 2;370 var barHeight;371 var x = 0;372 var middlePoint = Math.ceil(width / 2);373 BX.VideoRecorder.canvasContext.fillStyle = '#afb2b7';374 for(var i = 0; i < frequencyPoints; i++)375 {376 barHeight = Math.round(BX.VideoRecorder.frequencyData[i] * height / 256);377 //barHeight = Math.round(this.frequencyData[i] + 80);378 if(barHeight < 3)379 barHeight = 3;380 x = middlePoint + (barWidth + 2) * i;381 BX.VideoRecorder.canvasContext.fillRect(x, (height - barHeight) / 2 , barWidth, barHeight);382 x = middlePoint - (barWidth + 2) * i;383 BX.VideoRecorder.canvasContext.fillRect(x, (height - barHeight) / 2 , barWidth, barHeight);384 }385 BX.VideoRecorder.canvasContext.closePath();386 },387 getTimeString: function(seconds)388 {389 var time = '';390 var minutes = Math.floor(seconds / 60);391 if(minutes < 10)392 {393 time = '0';394 }395 time = time + minutes + ':';396 seconds = (seconds - (minutes*60));397 if(seconds < 10)398 {399 time = time + '0';400 }401 time = time + seconds;402 return time;403 },404 start: function(formId)405 {406 BX.VideoRecorder.transformLimit = BX.message('DISK_VIDEO_TRANSFORMATION_LIMIT') || 0;407 BX.VideoRecorder.activeFormID = formId;408 if(!BX.VideoRecorder.isAvailable(true))409 {410 var errorCode = 'BLOG_VIDEO_RECORD_REQUIREMENTS';411 if(BX.VideoRecorder.errorCode)412 {413 errorCode = BX.VideoRecorder.errorCode;414 }415 BX.VideoRecorder.showMessage(416 BX.message(errorCode),417 [],418 BX.message('BLOG_VIDEO_RECORD_REQUIREMENTS_TITLE')419 );420 }421 else if(BX.VideoRecorder.isPermissionsAsked())422 {423 BX.VideoRecorder.askDevicePermission();424 BX.VideoRecorder.showLayout();425 }426 else427 {428 BX.VideoRecorder.showMessage(BX.message('BLOG_VIDEO_RECORD_ASK_PERMISSIONS'), [429 new BX.PopupWindowButton({430 text : BX.message('BLOG_VIDEO_RECORD_AGREE'),431 className : "popup-window-button-blue",432 events : { click : function()433 {434 BX.VideoRecorder.popupPermissionsShown = true;435 BX.VideoRecorder.askDevicePermission();436 BX.VideoRecorder.showLayout();437 }}438 }),439 new BX.PopupWindowButtonLink({440 text : BX.message('BLOG_VIDEO_RECORD_CLOSE'),441 className : "popup-window-button-decline",442 events : { click : function() { this.popupWindow.close(); } }443 })444 ], BX.message('BLOG_VIDEO_RECORD_PERMISSIONS_TITLE'));445 }446 },447 askDevicePermission: function()448 {449 navigator.mediaDevices.getUserMedia(BX.VideoRecorder.constraints).then(function(stream)450 {451 BX.VideoRecorder.stream = stream;452 if(BX.VideoRecorder.popupConfirm)453 {454 BX.VideoRecorder.popupConfirm.destroy();455 }456 if(!BX.VideoRecorder.popupRecord)457 {458 BX.VideoRecorder.hideLayout();459 return;460 }461 BX.VideoRecorder.setVideoSrc(BX.VideoRecorder.stream);462 BX.VideoRecorder.outputVideo.play();463 }).catch(function(error)464 {465 BX.VideoRecorder.hideLayout();466 BX.VideoRecorder.showMessage(BX.message('BLOG_VIDEO_RECORD_PERMISSIONS_ERROR'), [], BX.message('BLOG_VIDEO_RECORD_PERMISSIONS_ERROR_TITLE'));467 BX.VideoRecorder.popupPermissionsShown = false;468 console.log(error);469 });470 },471 showMessage: function(content, buttons, title)472 {473 var autohide = false;474 var title = title || '';475 if (typeof(buttons) == "undefined" || typeof(buttons) == "object" && buttons.length <= 0)476 {477 buttons = [new BX.PopupWindowButton({478 text : BX.message('BLOG_VIDEO_RECORD_CLOSE'),479 className : "popup-window-button-blue",480 events : { click : function(e) { this.popupWindow.close(); BX.PreventDefault(e) } }481 })];482 autohide = true;483 }484 if(this.popupConfirm != null)485 {486 this.popupConfirm.destroy();487 }488 this.popupConfirm = new BX.PopupWindow('bx-popup-videomessage-popup', null, {489 zIndex: 200,490 autoHide: autohide,491 closeByEsc: autohide,492 buttons: buttons,493 overlay : true,494 events : { onPopupClose : function() { this.destroy() }, onPopupDestroy : BX.delegate(function() { this.popupConfirm = null }, this)},495 content : content,496 titleBar: title,497 contentColor: 'white',498 className : 'bx-popup-videomessage-popup'499 });500 this.popupConfirm.show();501 },502 hideLayout: function()503 {504 if(BX.VideoRecorder.recorder && BX.VideoRecorder.recorder.state === 'recording')505 {506 BX.VideoRecorder.recorder.stop();507 }508 if(BX.VideoRecorder.outputVideo)509 {510 BX.VideoRecorder.outputVideo.pause();511 }512 if (document.cancelFullScreen)513 {514 document.cancelFullScreen();515 }516 else if (document.mozCancelFullScreen)517 {518 document.mozCancelFullScreen();519 }520 else if (document.webkitCancelFullScreen)521 {522 document.webkitCancelFullScreen();523 }524 if(BX.VideoRecorder.popupRecord)525 {526 BX.VideoRecorder.popupRecord.destroy();527 }528 if(BX.VideoRecorder.layout)529 {530 BX.VideoRecorder.layout.remove();531 BX.VideoRecorder.layout = null;532 BX.VideoRecorder.analyzerElement = null;533 }534 if(BX.VideoRecorder.stream)535 {536 BX.VideoRecorder.stream.getVideoTracks().forEach(function(track) {537 track.stop();538 });539 BX.VideoRecorder.stream.getAudioTracks().forEach(function(track) {540 track.stop();541 });542 }543 BX.VideoRecorder.startCount = 0;544 clearInterval(BX.VideoRecorder.recordInterval);545 BX.VideoRecorder.panel.style.display = 'none';546 BX.VideoRecorder.waterMark.style.display = 'none';547 BX.VideoRecorder.buttonPlay.style.display = 'none';548 window.removeEventListener('resize', BX.VideoRecorder.resize);549 BX.VideoRecorder.unlockScroll();550 BX.VideoRecorder.hideTransformTimer();551 },552 resize: function()553 {554 if(!BX.VideoRecorder.popupRecord)555 {556 return;557 }558 var height = BX.VideoRecorder.getScreenHeight();559 var width = BX.VideoRecorder.getScreenWidth();560 var resultRelativeSize = width / height;561 var videoRelativeSize = BX.VideoRecorder.outputVideo.videoWidth / BX.VideoRecorder.outputVideo.videoHeight;562 if(resultRelativeSize > videoRelativeSize)563 {564 BX.VideoRecorder.outputVideo.width = width;565 BX.VideoRecorder.outputVideo.height = height * resultRelativeSize / videoRelativeSize;566 BX.VideoRecorder.outputVideo.style.marginTop = (height - height * resultRelativeSize / videoRelativeSize) / 2 + 'px';567 BX.VideoRecorder.outputVideo.style.marginLeft = 0;568 }569 else570 {571 BX.VideoRecorder.outputVideo.height = height;572 BX.VideoRecorder.outputVideo.width = width * videoRelativeSize / resultRelativeSize;573 BX.VideoRecorder.outputVideo.style.marginTop = 0;574 BX.VideoRecorder.outputVideo.style.marginLeft = (width - width * videoRelativeSize / resultRelativeSize) / 2 + 'px';575 }576 BX.VideoRecorder.videoOverlay.style.height = height + 'px';577 BX.VideoRecorder.videoContainer.style.height = height + 'px';578 BX.VideoRecorder.popupRecord.setHeight(height);579 BX.VideoRecorder.videoWrap.style.height = height + 'px';580 BX.VideoRecorder.videoWrap.style.width = BX.VideoRecorder.outputVideo.clientWidth + 'px';581 BX.VideoRecorder.panel.style.width = width + 'px';582 BX('popup-window-content-bx-popup-videomessage-record').style.width = width + 'px';583 BX.VideoRecorder.panel.style.display = 'block';584 BX.VideoRecorder.waterMark.style.display = 'block';585 },586 lockScroll: function()587 {588 BX.addClass(document.body, 'bx-videomessage-lock-scroll');589 },590 unlockScroll: function()591 {592 BX.removeClass(document.body, 'bx-videomessage-lock-scroll');593 },594 setVideoSrc: function(object)595 {596 if (BX.VideoRecorder.outputVideo.srcObject)597 {598 BX.VideoRecorder.outputVideo.srcObject = object;599 }600 else601 {602 BX.VideoRecorder.outputVideo.src = URL.createObjectURL(object);603 }604 },605 isTimeToShowTransformationAlert: function()606 {607 if(BX.VideoRecorder.transformLimit > 0 && !BX.VideoRecorder.transformTimerShown)608 {609 var derivative = BX.VideoRecorder.recordSize / BX.VideoRecorder.recordLength;610 BX.VideoRecorder.transformTimeLeft = Math.floor((BX.VideoRecorder.transformLimit - BX.VideoRecorder.recordSize) / derivative);611 if(BX.VideoRecorder.transformTimeLeft <= BX.VideoRecorder.transformTime)612 {613 if(BX.VideoRecorder.transformTimeLeft > 10)614 {615 BX.VideoRecorder.transformTimeLeft -= 10;616 }617 return true;618 }619 }620 return false;621 },622 startTransformationCounter: function()623 {624 if(!BX.VideoRecorder.transformTimerShown)625 {626 BX.VideoRecorder.transformTimerShown = true;627 BX.VideoRecorder.showTransformTimer();628 BX.VideoRecorder.transformTimer = setTimeout(function()629 {630 BX.VideoRecorder.hideTransformTimer();631 }, BX.VideoRecorder.transformTimeLeft * 1000);632 }633 },634 showTransformTimer: function()635 {636 BX.VideoRecorder.transformTimeContainer.classList.add('js-videomessage-transform-time-active');637 },638 hideTransformTimer: function()639 {640 BX.VideoRecorder.transformTimeContainer.classList.remove('js-videomessage-transform-time-active');641 },642 restartRecord: function()643 {644 BX.VideoRecorder.recordCount = 0;645 BX.VideoRecorder.recordTimer.innerText = BX.VideoRecorder.getTimeString(BX.VideoRecorder.recordCount);646 BX.VideoRecorder.startCount = 5;647 BX.VideoRecorder.state = 'idle';648 BX.VideoRecorder.transformTimeLeft = BX.VideoRecorder.transformTime;649 BX.VideoRecorder.transformTimerShown = false;650 BX.VideoRecorder.hideTransformTimer();651 BX.VideoRecorder.buttonStop.style.display = 'inline-block';652 BX.VideoRecorder.buttonPlay.style.display = 'none';653 BX.VideoRecorder.buttonSave.style.display = 'none';654 BX.VideoRecorder.buttonCancel.style.display = 'none';655 BX.VideoRecorder.buttonRestart.style.display = 'none';656 BX.VideoRecorder.videoOverlay.style.display = 'block';657 if(BX.VideoRecorder.stream)658 {659 BX.VideoRecorder.setVideoSrc(BX.VideoRecorder.stream);660 BX.VideoRecorder.outputVideo.play();661 }662 else663 {664 BX.VideoRecorder.askDevicePermission();665 }666 }667};668BX.addCustomEvent(window, 'onInitialized', function (handler) {669 BX.VideoRecorder.bindEvents(handler);670});...

Full Screen

Full Screen

useRecorder.js

Source:useRecorder.js Github

copy

Full Screen

1import { useCallback, useEffect, useRef, useState } from "react";2const defaultContraints = {3 audio: true,4 video: false,5};6// mediaRecorderOptions can be {7// mimeType?: string;8// audioBitsPerSecond?: number;9// videoBitsPerSecond?: number;10// bitsPerSecond?: number;11// }12function useRecorder(13 mediaStreamConstraints,14 mediaRecorderOptions = {15 mimeType: "audio/aac",16 }17) {18 const mediaRecorderRef = useRef();19 const streamRef = useRef();20 const [status, setStatus] = useState("init");21 const [error, setError] = useState();22 const register = useCallback((callback) => {23 //register sets up recorder and stream24 //calls passed function (in case, startRecording) after setup25 callback26 ? initRecording()27 .then((granted) => {28 granted && callback();29 })30 .catch(setError)31 : initRecording();32 }, []);33 const initRecording = useCallback(async () => {34 //getUserMedia will trigger browser permission prompt if access not granted35 try {36 await navigator.mediaDevices37 .getUserMedia({38 ...defaultContraints,39 ...(mediaStreamConstraints ? { ...mediaStreamConstraints } : {}),40 })41 .then((stream) => {42 //after grant, receives stream and sets up recorder43 streamRef.current = stream;44 let options = { mimeType: "audio/aac" };45 if (typeof MediaRecorder.isTypeSupported == "function") {46 /*47 MediaRecorder.isTypeSupported is a function announced in https://developers.google.com/web/updates/2016/01/mediarecorder and later introduced in the MediaRecorder API spec http://www.w3.org/TR/mediastream-recording/48 */49 if (MediaRecorder.isTypeSupported("audio/x-aac")) {50 options = { mimeType: "audio/x-aac" };51 } else if (MediaRecorder.isTypeSupported("audio/wav")) {52 options = { mimeType: "audio/wav" };53 } else if (MediaRecorder.isTypeSupported("audio/mpeg")) {54 options = { mimeType: "audio/mpeg" };55 } else if (MediaRecorder.isTypeSupported("audio/mp4")) {56 options = { mimeType: "audio/mp4" };57 } else if (MediaRecorder.isTypeSupported("audio/webm")) {58 options = { mimeType: "audio/webm" };59 } else if (MediaRecorder.isTypeSupported("audio/ogg")) {60 options = { mimeType: "audio/ogg" };61 } else if (MediaRecorder.isTypeSupported("audio/flac")) {62 options = { mimeType: "audio/flac" };63 } else if (MediaRecorder.isTypeSupported("audio/x-caf")) {64 options = { mimeType: "audio/x-caf" };65 } else if (MediaRecorder.isTypeSupported("audio/aac")) {66 //Safari 14.0.2 has an EXPERIMENTAL version of MediaRecorder enabled by default67 options = { mimeType: "audio/aac" };68 }69 }70 const recorder = new MediaRecorder(stream, options);71 mediaRecorderRef.current = recorder;72 setStatus("idle");73 });74 return true;75 } catch (err) {76 //set error encountered during setup77 //if permission explicitly blocked by user => set error access blocked78 typeof err === "object" ? setError("Access Blocked") : setError(err);79 return false;80 }81 }, []);82 const startRecording = useCallback(() => {83 setStatus("recording");84 mediaRecorderRef?.current?.start();85 }, []);86 const pauseRecording = useCallback(() => {87 setStatus("paused");88 mediaRecorderRef.current?.pause();89 }, []);90 const resumeRecording = useCallback(() => {91 setStatus("recording");92 mediaRecorderRef.current?.resume();93 }, []);94 const stopRecording = useCallback(95 (callback) => () => {96 setStatus("idle");97 if (mediaRecorderRef.current) {98 //push recorder data into chunks and create audio blob and url99 mediaRecorderRef.current.ondataavailable = (e) => {100 let chunks = [];101 chunks.push(e.data);102 let options = { type: "audio/aac" };103 if (typeof MediaRecorder.isTypeSupported == "function") {104 /*105 MediaRecorder.isTypeSupported is a function announced in https://developers.google.com/web/updates/2016/01/mediarecorder and later introduced in the MediaRecorder API spec http://www.w3.org/TR/mediastream-recording/106 */107 if (MediaRecorder.isTypeSupported("audio/x-aac")) {108 options = { type: "audio/x-aac" };109 } else if (MediaRecorder.isTypeSupported("audio/wav")) {110 options = { type: "audio/wav" };111 } else if (MediaRecorder.isTypeSupported("audio/mpeg")) {112 options = { type: "audio/mpeg" };113 } else if (MediaRecorder.isTypeSupported("audio/mp4")) {114 options = { type: "audio/mp4" };115 } else if (MediaRecorder.isTypeSupported("audio/webm")) {116 options = { type: "audio/webm" };117 } else if (MediaRecorder.isTypeSupported("audio/ogg")) {118 options = { type: "audio/ogg" };119 } else if (MediaRecorder.isTypeSupported("audio/flac")) {120 options = { type: "audio/flac" };121 } else if (MediaRecorder.isTypeSupported("audio/x-caf")) {122 options = { type: "audio/x-caf" };123 } else if (MediaRecorder.isTypeSupported("audio/aac")) {124 //Safari 14.0.2 has an EXPERIMENTAL version of MediaRecorder enabled by default125 options = { type: "audio/aac" };126 }127 }128 const blob = new Blob(chunks, options);129 let audioURL = window.URL.createObjectURL(blob);130 try {131 audioURL = window.webkitURL.createObjectURL(blob);132 } catch {133 audioURL = window.URL.createObjectURL(blob);134 }135 callback(blob, audioURL);136 };137 mediaRecorderRef.current?.stop();138 }139 },140 []141 );142 // Only Chrome has support for microphone, camera query. Helps in determining explicit block143 const getPermissionStatus = useCallback(async () => {144 let permissionsStatus;145 await navigator.permissions146 .query({ name: "microphone" })147 .then((result) => (permissionsStatus = result.state));148 return permissionsStatus;149 }, []);150 if (!navigator.mediaDevices) {151 console.log("Navigator is not compatible");152 }153 //stream cleanup function154 const stopMediaStream = useCallback(() => {155 const stream = streamRef?.current;156 if (stream) {157 if (stream.getAudioTracks) {158 stream.getVideoTracks().map((track) => {159 stream.removeTrack(track);160 track.stop();161 });162 stream.getAudioTracks().map((track) => {163 stream.removeTrack(track);164 track.stop();165 });166 } else {167 stream.stop();168 }169 }170 }, [streamRef]);171 //cleanup stream on unmount172 useEffect(() => {173 return () => {174 stopMediaStream();175 };176 }, []);177 return {178 mediaRecorder: mediaRecorderRef?.current,179 stream: streamRef?.current,180 getPermissionStatus,181 register,182 startRecording,183 pauseRecording,184 resumeRecording,185 stopRecording,186 status,187 error,188 };189}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { recorder } = require('differencify')2const { recorder } = require('differencify')3const { recorder } = require('differencify')4const { recorder } = require('differencify')5const { recorder } = require('differencify')6const { recorder } = require('differencify')7const { recorder } = require('differencify')8const { recorder } = require('differencify')9const { recorder } = require('differencify')10const { recorder } = require('differencify')11const { recorder } = require('differencify')12const { recorder } = require('differencify')13const { recorder } = require('differencify')14const { recorder } = require('differencify')15const { recorder } = require('differencify')16const { recorder } = require('differencify')17const { recorder } = require('differencify')18const { recorder } = require('differencify')19const { recorder } = require('differencify')20const { recorder } = require('differencify')21const { recorder } = require('differencify')22const { recorder } = require('differencify')

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2differencify.init(browser, { autoSaveBaseline: true });3describe('My First Test', function() {4 it('Does not do much!', function() {5 differencify.recorder('google');6 });7});8differencify.cleanup();9const differencify = require('differencify');10exports.config = {11 differencifyOpts: {12 {13 }14 {15 }16 }17};18differencify.cleanup();19differencify.recorder('google');20browser.saveFullPageScreen('google', {21});22browser.saveElement('.adsbygoogle', 'google', {23});24browser.saveElement('.adsbygoogle', 'google', {25});26browser.saveElement('.adsbygoogle', 'google', {27});28browser.saveElement('.adsbygoogle', 'google', {29});30browser.saveElement('.adsbygoogle', 'google', {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { recorder } = require('differencify');2const { expect } = require('chai');3const webdriverio = require('webdriverio');4const chrome = require('selenium-webdriver/chrome');5const path = require('chromedriver').path;6const opts = {7 desiredCapabilities: {8 },9};10const browser = webdriverio.remote(opts);11recorder.init(browser);12describe('Google', () => {13 before(async () => {14 await browser.init();15 });16 after(async () => {17 await browser.end();18 });19 it('should display the correct title', async () => {20 const title = await browser.getTitle();21 expect(title).to.equal('Google');22 });23 it('should display the correct title', async () => {24 const title = await browser.getTitle();25 expect(title).to.equal('Google');26 });27});28recorder.stop();29### `recorder.init(browser)`30### `recorder.stop()`31### `recorder.start()`32### `recorder.pause()`33### `recorder.resume()`34### `recorder.isPaused()`35### `recorder.isRunning()`36### `recorder.isStopped()`37### `recorder.setOptions(options)`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { recorder } = require('differencify');2const { launch } = require('puppeteer');3(async () => {4 const browser = await launch();5 const page = await browser.newPage();6 await recorder(page, 'test', { threshold: 0.1 });7 await page.screenshot({ path: 'google.png' });8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1require('differencify').recorder();2const { compareScreenshot } = require('differencify');3describe('My First Test', function() {4 it('Does not do much!', function() {5 cy.contains('type').click();6 cy.get('.action-email')7 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const recorder = require('differencify').recorder2const {expect} = require('chai')3describe('Test', function () {4 it('should pass', async function () {5 await recorder.start()6 const title = await browser.getTitle()7 await recorder.stop()8 expect(title).to.equal('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')9 })10})11exports.config = {12 plugins: {13 'differencify': {14 baselineFolder: join(process.cwd(), './tests/selenium/baseline/'),15 formatImageName: '{tag}-{logName}-{width}x{height}',16 screenshotPath: join(process.cwd(), './tests/selenium/'),17 }18 }19}20{21 "scripts": {22 },23 "devDependencies": {24 }25}

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2differencify.init(browser, {3});4differencify.run(async () => {5 await browser.saveElement('body', 'body-element');6 await browser.saveElement($('body'), 'body-element');7});8differencify.finish();9differencify.assert();10differencify.assertElement('body', 'body-element');11differencify.assertElement($('body'), 'body-element');12differencify.assertElement($('body'), 'body-element', {13});14differencify.assertElements(['body', 'header'], 'body-element');15differencify.assertElements(['body', 'header'], 'body-element', {16});17differencify.assertElements([$('body'), $('header')], 'body-element');18differencify.assertElements([$('body'), $('header')], 'body-element', {19});20differencify.assertScreen('body-element');21differencify.assertScreen('body-element', {22});23differencify.assertViewport('body-element');24differencify.assertViewport('body-element', {25});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run differencify 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