首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何处理http实时流HLS的生命周期?

如何处理http实时流HLS的生命周期?
EN

Stack Overflow用户
提问于 2017-09-07 14:17:11
回答 1查看 1.7K关注 0票数 0

我使用这个hls.js播放器以及对流m3u8的反应。我有一个组件VideoPlayer来设置hls.js播放器。这个组件有一些状态属性,比如isPlayingisMuted。我有自定义按钮,onClick调用组件函数到setState,但这当然是重新呈现组件和视频流重新挂载,我猜是回到原来的状态,这是回到它的第一个帧,并停止。通常,如何处理流视频的应用程序(redux)或本地状态更改?我注意到视频总是有这个“闪烁”(它是重新呈现),在任何时候,redux存储更新,或本地状态变化。

用代码示例更新

代码语言:javascript
运行
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2017-09-10 11:06:10

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

playVideo -> setState -> componentUpdate -> componentDidUpdate -> initPlayer

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

您可以覆盖"shouldComponentUpdate“,以防止更新而不初始化播放机。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46098703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档