如何使用HTTP实时流媒体HLS处理反应生命周期



我正在使用此HLS.JS播放器以及对流M3U8的React。我有一个组件VideoPlayer可以设置HLS.JS播放器。该组件具有几个状态属性,例如isPlayingisMuted。我的自定义按钮将onClick调用组件函数为setState,但是这当然可以重新呈现组件和视频流重新安装,我猜回到了它的原始状态,该状态又回到了它的第一帧并停止了。通常,您如何通过流视频处理应用程序(REDUX)或本地状态更改?我注意到这些视频始终具有这种"闪烁"(正在重新渲染),任何时候Redux Store更新或本地状态更改时。

更新代码示例:

import React, {PropTypes} from 'react';
import Hls from 'hls.js';
class VideoPlayer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isMuted: true,
      isPlaying: false,
      playerId : Date.now()
    };
    this.hls = null;
    this.playVideo = this.playVideo.bind(this);
  }
  componentDidMount() {
    this._initPlayer();
  }
  componentDidUpdate() {
    this._initPlayer();
  }
  componentWillUnmount() {
    if(this.hls) {
      this.hls.destroy();
    }
  }
  playVideo() {
    let { video : $video } = this.refs;
    $video.play();
    this.setState({isPlaying: true});
  }
  _initPlayer () {
    if(this.hls) {
      this.hls.destroy();
    }
    let { url, autoplay, hlsConfig } = this.props;
    let { video : $video } = this.refs;
    let hls = new Hls(hlsConfig);
    hls.attachMedia($video);
    hls.on(Hls.Events.MEDIA_ATTACHED, () => {
      hls.loadSource(url);
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        if(autoplay) {
          $video.play();
        }
        else {
          $video.pause();
        }
      });
    });
    this.hls = hls;
  }
  render() {
    let { isMuted, isPlaying, playerId } = this.state;
    let { controls, width, height } = this.props;
    return (
      <div key={playerId}>
        {!isPlaying &&
          <span onClick={this.playVideo}></span>
        }
        <video ref="video"
          id={`react-hls-${playerId}`}
          controls={controls}
          width={width}
          height={height}
          muted={isMuted}
          playsinline>
        </video>
      </div>
    );
  }
}
export default VideoPlayer;

我认为问题是组件的生命周期。

playVideo-> setState-> componentupdate-> componentDidupdate-> initplayer

因此,每次用户播放视频时都会初始化播放器。

您可以覆盖"应该componentupdate",因此请不要在不初始化播放器的情况下进行更新。


最新更新