import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; import styles from './index.less'; export default class RBVideoPlayer extends PureComponent { static propTypes = { url: PropTypes.string.isRequired, autoplay: PropTypes.bool, hlsConfig: PropTypes.object, // https://github.com/dailymotion/hls.js/blob/master/API.md#fine-tuning controls: PropTypes.bool, width: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), height: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), poster: PropTypes.string, videoProps: PropTypes.object, }; static defaultProps = { autoplay: false, hlsConfig: {}, controls: true, width: 500, height: 375, }; constructor(props) { super(props); this.state = { playerId: Date.now(), }; this.hls = null; } componentDidUpdate() { if (this.props.isM3U8) { this._initPlayer(); } } componentDidMount() { if (this.props.isM3U8) { this._initPlayer(); } } componentWillUnmount() { if (this.hls) { this.hls.destroy(); } } _initPlayer() { if (this.hls) { this.hls.destroy(); } const { url, autoplay, hlsConfig } = this.props; const { video: $video } = this.refs; const hls = new Hls(hlsConfig); hls.loadSource(url); hls.attachMedia($video); hls.on(Hls.Events.MANIFEST_PARSED, () => { if (autoplay) { $video.play(); } }); this.hls = hls; } render() { const { playerId } = this.state; const { url, controls, width, height, poster, videoProps } = this.props; return (
); } }