index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import React, { PureComponent } from 'react';
  2. import PropTypes from 'prop-types';
  3. import Hls from 'hls.js';
  4. import styles from './index.less';
  5. export default class RBVideoPlayer extends PureComponent {
  6. static propTypes = {
  7. url: PropTypes.string.isRequired,
  8. autoplay: PropTypes.bool,
  9. hlsConfig: PropTypes.object, // https://github.com/dailymotion/hls.js/blob/master/API.md#fine-tuning
  10. controls: PropTypes.bool,
  11. width: PropTypes.oneOfType([
  12. PropTypes.number,
  13. PropTypes.string,
  14. ]),
  15. height: PropTypes.oneOfType([
  16. PropTypes.number,
  17. PropTypes.string,
  18. ]),
  19. poster: PropTypes.string,
  20. videoProps: PropTypes.object,
  21. };
  22. static defaultProps = {
  23. autoplay: false,
  24. hlsConfig: {},
  25. controls: true,
  26. width: 500,
  27. height: 375,
  28. };
  29. constructor(props) {
  30. super(props);
  31. this.state = {
  32. playerId: Date.now(),
  33. };
  34. this.hls = null;
  35. }
  36. componentDidUpdate() {
  37. if (this.props.isM3U8) {
  38. this._initPlayer();
  39. }
  40. }
  41. componentDidMount() {
  42. if (this.props.isM3U8) {
  43. this._initPlayer();
  44. }
  45. }
  46. componentWillUnmount() {
  47. if (this.hls) {
  48. this.hls.destroy();
  49. }
  50. }
  51. _initPlayer() {
  52. if (this.hls) {
  53. this.hls.destroy();
  54. }
  55. const { url, autoplay, hlsConfig } = this.props;
  56. const { video: $video } = this.refs;
  57. const hls = new Hls(hlsConfig);
  58. hls.loadSource(url);
  59. hls.attachMedia($video);
  60. hls.on(Hls.Events.MANIFEST_PARSED, () => {
  61. if (autoplay) {
  62. $video.play();
  63. }
  64. });
  65. this.hls = hls;
  66. }
  67. render() {
  68. const { playerId } = this.state;
  69. const { url, controls, width, height, poster, videoProps } = this.props;
  70. return (
  71. <div key={playerId} className={styles.playerArea}>
  72. <video
  73. ref="video"
  74. className={styles.hlsVideo}
  75. id={`react-hls-${playerId}`}
  76. controls={controls}
  77. width={width}
  78. height={height}
  79. src={url}
  80. poster={poster}
  81. {...videoProps}
  82. />
  83. </div>
  84. );
  85. }
  86. }