【发布时间】:2017-09-07 14:17:11
【问题描述】:
我正在使用这个 hls.js player 和 React 来流式传输 m3u8。我有一个组件 VideoPlayer 来设置 hls.js 播放器。这个组件有几个状态属性,比如isPlaying 和isMuted。我有自定义按钮,onClick 将组件函数调用到setState,但这当然会重新渲染组件,并且我猜视频流会重新挂载并恢复到原始状态,即恢复到第一帧和停了下来。一般来说,您如何处理流视频的应用程序(redux)或本地状态更改?我注意到,每当 redux 商店更新或本地状态发生变化时,视频总是会出现这种“闪烁”(即重新渲染)。
更新代码示例:
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;
【问题讨论】:
-
我们无法猜测您如何实现组件来帮助您。请更新更多细节。
标签: reactjs redux rendering http-live-streaming hls.js