{"size": 1731, "ext": "js", "max_stars_repo_path": "packages/react/src/FlvPlayer.js", "max_stars_repo_name": "yslin9901/JS-Library", "max_stars_repo_stars_event_min_datetime": "2021-04-15T05:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T16:38:39.000Z", "max_issues_repo_path": "packages/react/src/FlvPlayer.js", "max_issues_repo_name": "yslin9901/JS-Library", "max_issues_repo_issues_event_min_datetime": "2021-09-17T05:26:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T05:26:15.000Z", "max_forks_repo_path": "packages/react/src/FlvPlayer.js", "max_forks_repo_name": "yslin9901/JS-Library", "max_forks_repo_forks_event_min_datetime": "2021-08-23T09:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T09:55:06.000Z"}
{"max_stars_count": 2, "max_issues_count": 1, "max_forks_count": 1, "avg_line_length": 25.0869565217, "max_line_length": 73, "alphanum_fraction": 0.6123627961}
import React, {useRef, useEffect} from 'react';
import PropTypes from 'prop-types';
import flvjs from 'flv.js';
import {Requests} from '@skywatch/api';

const FlvPlayer = ({
  deviceId,
  onPlayerInit,
  onPlayerDispose,
  style,
  controls,
  onReady,
}) => {
  const containerRef = useRef(null);
  useEffect(() => {
    const initPlayer = async () => {
      const res = await Requests.getFlvStream(deviceId);
      if (res.data && flvjs.isSupported() && containerRef.current) {
        const videoEl = containerRef.current.querySelector('video');
        const flvPlayer = flvjs.createPlayer({
          type: 'flv',
          url: res.data,
          config: {
            enableWorker: true,
            enableStashBuffer: false,
            stashInitialSize: 128,
          },
        });
        flvPlayer.attachMediaElement(videoEl);
        flvPlayer.load();
        flvPlayer.play().then(() => onReady());
        flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
          console.log(errType, errDetail);
        });

        onPlayerInit && onPlayerInit(flvPlayer);
      }
      return () => {
        onPlayerDispose && onPlayerDispose(null);
        flvPlayer.destroy();
      };
    };

    initPlayer();
  }, []);

  return (
    <div className="player" ref={containerRef}>
      <video id="videoElement" controls={controls} muted style={style} />
    </div>
  );
};

FlvPlayer.defaultProps = {
  controls: true,
  onReady: () => {},
};

FlvPlayer.propTypes = {
  deviceId: PropTypes.string.isRequired,
  onPlayerInit: PropTypes.func.isRequired,
  onPlayerDispose: PropTypes.func.isRequired,
  style: PropTypes.object,
  controls: PropTypes.bool,
  onReady: PropTypes.func,
};

export default FlvPlayer;
