sak1b

attachmediastream.ts

Jul 13th, 2021 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import adapter from 'webrtc-adapter';
  2. //https://github.com/otalk/attachMediaStream/blob/master/attachmediastream.js
  3. // eslint-disable-next-line import/no-anonymous-default-export
  4. export default function (el : any, stream : any, options : any = null) {
  5.   let item;
  6.   let element = el;
  7.   const opts: any = {
  8.     autoplay: true,
  9.     mirror: false,
  10.     muted: false,
  11.     audio: false,
  12.     disableContextMenu: false
  13.   };
  14.  
  15.   if (options) {
  16.     for (item   in options) {
  17.       opts[item] = options[item];
  18.     }
  19.   }
  20.  
  21.   if (!element) {
  22.     //@ts-ignore
  23.     element = document.createElement(opts.audio ? 'audio' : 'video');
  24.   } else if (element.tagName.toLowerCase() === 'audio') {
  25.     opts.audio = true;
  26.   }
  27.  
  28.   if (opts.disableContextMenu) {
  29.     element.oncontextmenu = function (e : any) {
  30.       e.preventDefault();
  31.     };
  32.   }
  33.  
  34.   if (opts.autoplay) element.autoplay = 'autoplay';
  35.   element.muted = opts.muted;
  36.   if (!opts.audio) {
  37.     ['', 'moz', 'webkit', 'o', 'ms'].forEach(function (prefix) {
  38.       const styleName = prefix ? prefix + 'Transform' : 'transform';
  39.       element.style[styleName] = opts.mirror ? 'scaleX(-1)' : 'scaleX(1)';
  40.     });
  41.   }
  42.  
  43.   if (adapter.browserDetails.browser === 'safari') {
  44.     element.setAttribute('playsinline', true);
  45.   }
  46.  
  47.   element.srcObject = stream;
  48.  
  49.   try {
  50.     element.srcObject = stream;
  51.   } catch (e) {
  52.     try {
  53.       //@ts-ignore
  54.       element.src = URL.createObjectURL(stream);
  55.     } catch (e) {
  56.       throw new Error("Error attaching stream to element");
  57.     }
  58.   }
  59.   return element;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment