flv.js

yuhuo2022-11-26开发库工具库
参考链接

直播协议 HTTP-FLV

<video id="flv_player" width="600" height="400" controls muted></video>
<button onclick="pause()">暂停</button>
<button onclick="play()">播放</button>
<button onclick="setCurrent()">同步</button>
<script src="https://cdn.bootcss.com/flv.js/1.6.2/flv.min.js"></script>
<script>
    let isPlaying = false;
    if (flvjs.isSupported()) {
        var flvVideo = document.getElementById("flv_player");
        var flvPlayer = flvjs.createPlayer({
            type: "flv",
            // url: "../../static/video/tinify_cdn.flv",
            // copy虎牙的链接
            url: "https://hz6xyk83.v2l.szbdyd.com:9306/xy-flv-live.huya-noidc.xycdn.com/xy_live/3cfe1a471a3c852cd0b605921aa92979.flv?xy3rdUrl=https%3A%2F%2Fhw.flv.huya.com%2Fsrc%2F1099531627955-1099531627955-85900114719145984-2199063379366-10057-A-0-1_ratio%3D2000.flv%3FwsSecret%3Db6845964b78f782cfa4ad7a3b7e7138c%26wsTime%3D6406f446%26seqid%3D3143531248748%26ctype%3Dhuya_live%26ver%3D1%26fs%3Dbgct%26sphdcdn%3Dal_7-tx_3-js_3-ws_7-bd_2-hw_2%26sphdDC%3Dhuya%26sphd%3D264_*-265_*%26exsphd%3D264_500%2C264_2000%2C264_4000%2C%26ratio%3D2000%26pulltype%3Dpcdn%26u%3D1468436588845%26t%3D100%26sv%3D2208171613&xys=1678177376&xyt=835f6cc457fa3d9b9c03fc4c2143cc04&xy_dts=10575446",
        });
        flvPlayer.attachMediaElement(flvVideo);
        play();
        listen();
    }
    // 暂停直播:断开链接
    function pause() {
        if (isPlaying) {
            flvPlayer.unload();
            isPlaying = false;
        }
    }
    // 播放直播:加载链接,播放
    function play() {
        if (!isPlaying) {
            flvPlayer.load();
            flvPlayer.play();
            isPlaying = true;
        }
    }
    // 同步
    function setCurrent() {
        let endTime = flvVideo.buffered.end(0);
        // 如果当前进度落后最新缓存超过2秒,则设为落后2秒
        if(flvVideo.currentTime < endTime - 2) {
            flvVideo.currentTime = endTime - 2;
        }
    }

    // 监听错误事件
    function listen() {
        // 加载完成事件
        flvPlayer.on(flvjs.Events.METADATA_ARRIVED, () => {
            console.log("视频加载完成");
        });
        // 异常
        flvPlayer.on(flvjs.Events.ERROR, (err, errdet) => {
            // flvjs.ErrorTypes:表示一级异常
            // flvjs.ErrorDetails:表示二级异常
            // 参数 err 是一级异常,errdet 是二级异常
            if (err == flvjs.ErrorTypes.MEDIA_ERROR) {
                console.log("媒体错误");
                if (errdet == flvjs.ErrorDetails.MEDIA_FORMAT_UNSUPPORTED) {
                    console.log("媒体格式不支持");
                }
            }
            if (err == flvjs.ErrorTypes.NETWORK_ERROR) {
                console.log("网络错误");
                if (errdet == flvjs.ErrorDetails.NETWORK_STATUS_CODE_INVALID) {
                    console.log("http状态码异常");
                }
            }
            if (err == flvjs.ErrorTypes.OTHER_ERROR) {
                console.log("其他异常:", errdet);
            }
        });
    }
</script>
Last Updated 2024/3/14 09:51:53