flvCom.js 2.05 KB
import React, { Component } from "react"
import flvjs from "flv.js";
import "./flvCom.css"
export default class FlvCom extends Component {
    constructor(props){
        super(props);
        this.state = {
            id:new Date().getTime()+Math.floor(Math.random() * (10000 - 1)) + 1,
        }
    }
    shouldComponentUpdate(nextProps){
        if(nextProps.videoUrl!==this.props.videoUrl){
            if(this.flvPlayer){
                this.destroyFlv()
            }
            this.startFlv(nextProps.videoUrl)
            return true
        }
        return false
    }
    componentDidMount(){
        if(this.props.videoUrl){
            this.startFlv(this.props.videoUrl)
        }
    }
    startFlv(videoUrl){
        let {id} = this.state
        if (flvjs.isSupported()) {
            const videoElement = document.getElementById(id);
            if(this.flvPlayer) this.destroyFlv()
            this.flvPlayer = flvjs.createPlayer(
              {
                type: "flv",
                isLive: true,
                hasAudio: false,
                //必须与node搭建的流媒体服务器中的http的端口和推流的参数吻合
                url: videoUrl,
              },
              {
                enableStashBuffer: true,
                stashInitialSize: 128,
              }
            );
            this.flvPlayer.attachMediaElement(videoElement);
            this.flvPlayer.load();
            this.flvPlayer.play();
          } else {
              alert("请更换浏览器,该浏览器暂不支持。")
          }
    }
    destroyFlv(){
        this.flvPlayer.pause();
        this.flvPlayer.unload();
        this.flvPlayer.detachMediaElement();
        this.flvPlayer.destroy();
        this.flvPlayer = null;
    }
    render() {
        return (
            <div className="flvWai">
                <video
                    id={this.state.id}
                    className="videoFlv"
                    autoPlay
                    controls
                    muted
                ></video>
            </div>
        )
    }
}