1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 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 (
- <div key={playerId} className={styles.playerArea}>
- <video
- ref="video"
- className={styles.hlsVideo}
- id={`react-hls-${playerId}`}
- controls={controls}
- width={width}
- height={height}
- src={url}
- poster={poster}
- {...videoProps}
- />
- </div>
- );
- }
- }
|