manniru
5/20/2017 - 1:48 PM

Failed experiment of trying to render Youtube iframes as videos for react-vr. Fails because of cross origin iframes :(

Failed experiment of trying to render Youtube iframes as videos for react-vr. Fails because of cross origin iframes :(

import YoutubePlayer from 'youtube-player';
import html2canvas from 'html2canvas';

export default class YoutubeVideoPlayer {
  onMediaEvent: ?(any) => void;
  videoElement: HTMLVideoElement;
  _muted: boolean;
  _volume: number;

  static supportedFormats: ?Array<string> = ['youtube'];

  constructor() {
    this.videoElement = document.createElement('canvas');
    this.iframeElement = document.createElement('div');
    this.iframeElement.id = 'youtube-video-player';
    this.iframeElement.style.display = 'none';
    if (document.body) {
      document.body.appendChild(this.iframeElement);
    }

    this.player = null;

    this._volume = 1.0;
    this._muted = false;

    this.onMediaEvent = undefined;
    (this: any)._onMediaEvent = this._onMediaEvent.bind(this);
  }

  _convertToCanvas(callback) {
    const convert = () => {
      if (this.videoElement !== null) {
        html2canvas('youtube-video-player').then(function(canvas) {
          this.videoElement = canvas;
        });
      }

      window.requestAnimationFrame(convert);
    }

    convert();
  }

  initializeVideo(src: string, metaData: any) {
    this.player = YoutubePlayer('youtube-video-player', {
      videoId: src
    });
    this._bindMediaEvents();
    this.play();
  }

  hasEnoughData(): boolean {
    return true;
  }

  _onMediaEvent(event: any) {
    if (typeof this.onMediaEvent === 'function') {
      this.onMediaEvent(event);
    }
  }

  play() {
    this.player.playVideo().then(() => {
      this._convertToCanvas();
    });
  }

  pause() {
    this.player.stopVideo();
  }

  dispose() {
    this.pause();
    if (document.body) {
      document.body.removeChild(this.iframeElement);
    }
    this._unbindMediaEvents();
    this.onMediaEvent = undefined;
  }
}