我使用这个hls.js播放器以及对流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;
发布于 2017-09-10 11:06:10
我认为问题在于组件的生命周期。
playVideo -> setState -> componentUpdate -> componentDidUpdate -> initPlayer
因此,每当用户播放视频时,播放器都会被初始化。
您可以覆盖"shouldComponentUpdate“,以防止更新而不初始化播放机。
https://stackoverflow.com/questions/46098703
复制相似问题