我正在使用OBS创建实时视频流,并且正在使用 flv播放器来加载此视频流。但是,当我用componentDidUpdate
调用this.buildPlayer();
方法时,我继续遇到以下错误。我必须更新组件以向播放器重新加载流,但是最终出现以下错误,
TypeError: mediaElement is undefined
attachMediaElement
node_modules/flv.js/src/player/flv-player.js:131
128 |
129 | attachMediaElement(mediaElement) {
130 | this._mediaElement = mediaElement;
> 131 | mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
| ^ 132 | mediaElement.addEventListener('seeking', this.e.onvSeeking);
133 | mediaElement.addEventListener('canplay', this.e.onvCanPlay);
134 | mediaElement.addEventListener('stalled', this.e.onvStalled);
下面给出的代码:
constructor(props) {
super(props);
this.videoRef = React.createRef();
console.log(this.videoRef);
}
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchStream(id);
this.buildPlayer();
}
componentDidUpdate() {
this.buildPlayer();
}
componentWillUnmount() {
this.player.destroy();
}
buildPlayer() {
if (this.player || !this.props.stream) {
return;
}
const { id } = this.props.match.params;
this.player = flv.createPlayer({
type: 'flv',
url: `http://localhost:8000/live/${id}.flv`
});
console.log('Current Video Ref');
console.log(this.videoRef.current);
console.log('Player');
console.log(this.player);
this.player.attachMediaElement(this.videoRef.currnet);
this.player.load();
}
render() {
if (!this.props.stream) {
return <div>Loading...</div>;
}
const { title, description } = this.props.stream;
return (
<div>
<video ref={this.videoRef} style={{ width: '100%' }} controls />
<h1>{title}</h1>
<h5>{description}</h5>
</div>
);
}
不确定是什么原因导致其失败。如果我从componentDidUpdate()
方法中删除了调用,代码运行得很好,但是由于没有刷新,因此视频无法加载。我在做什么错了?
答案 0 :(得分:0)
“如果我从
componentDidUpdate()
方法中删除调用,代码运行得很好,但是由于没有刷新,视频无法加载。我在做什么错了?” >
代码中的return;
命令可能正在退出您的函数。
这意味着没有机会初始化新的视频播放器。
尝试:
buildPlayer()
{
if (this.player || !this.props.stream)
{
var msg = "If you see this message:" + "\r\n" + "Then your old code would stop here..." + "\r\n" + "Result = No video object created";
alert( msg );
//# the "return" command will exit (quit) your function at this point.
//# so any stuff below the "return;" line will NOT happen....
//return;
}
const { id } = this.props.match.params;
var myType = 'flv';
var myURL = 'http://localhost:8000/live/${id}.flv';
this.player = flv.createPlayer({ type: myType, url: myURL });
console.log('Current Video Ref');
console.log(this.videoRef.current);
console.log('Player');
console.log(this.player);
this.player.attachMediaElement(this.videoRef.current);
this.player.load();
}