我正在使用這個hls.js player以及React流m3u8。我有一個組件VideoPlayer
,它設置了hls.js播放器。該組件有幾個狀態屬性,如isPlaying
和isMuted
。我有自定義按鈕onClick
調用組件函數setState
,但這當然重新呈現組件和視頻流重新裝入我猜,並回到它的原始狀態,這是它回到它的第一幀並停止。一般來說,您如何處理應用程序(redux)或流式視頻的本地狀態更改?我注意到,無論任何時候redux商店更新或本地狀態更改,視頻總是會有「閃爍」(這是重新呈現)。如何使用http直播HLS處理React生命週期?
的代碼示例更新:
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;
我們無法猜測您如何實施您的組件來幫助您。請更新更多細節。 –