mpegts.js播放http/ts示例

直接上代码,简单的页面播放一个http/ts的直播

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ts player</title>
</head>
<body>
    <div>
        <video name="videoElement" width="640" height="480" controls="" muted="true" autoplay="">
            Your browser is too old which doesn't support HTML5 video.
        </video>
    </div>

    <script src="./mpegts.js"></script>
    <script>
        var check_count = 0;
        function player_load() {
            var mediaDataSource = {
                type: 'mse'
            };
            mediaDataSource.isLive = true;
            mediaDataSource.withCredentials = false;
            mediaDataSource.liveBufferLatencyChasing = true;
            mediaDataSource.url = "http://127.0.0.1:38080/ts/ok";
            player_load_mds(mediaDataSource);
        }

        function player_load_mds(mediaDataSource) {
            check_count = 0;
            var element = document.getElementsByName('videoElement')[0];
            if (typeof player !== "undefined") {
                if (player != null) {
                    player.unload();
                    player.detachMediaElement();
                    player.destroy();
                    player = null;
                }
            }
            player = mpegts.createPlayer(mediaDataSource, {
                enableWorker: true,
                lazyLoadMaxDuration: 3,
                liveBufferLatencyChasing: true,
            });
            player.on(mpegts.Events.LOADING_COMPLETE, function () {
                player_load();
            });
            player.on(mpegts.Events.ERROR, function () {
                player_load();
            });
            player.on(mpegts.Events.STATISTICS_INFO, (statisticsInfo) => {
                //console.log(JSON.stringify(statisticsInfo));
                if (statisticsInfo.speed > 1) {
                    check_count = 0;
                }
            });
            element.controls = false;
            player.attachMediaElement(element);
            player.load();
            check_count = 0;
        }

        function player_start() { player.play(); }
        function player_destroy() {
            player.pause();
            player.unload();
            player.detachMediaElement();
            player.destroy();
            player = null;
        }
        document.addEventListener('DOMContentLoaded', function () {
            player_load();
        });
        setInterval(function () {
            check_count += 1;
            if (check_count > 3) { player_load(); }
        }, 1000);
    </script>
</body>
</html>

 

posted on 2024-06-21 23:58  弘道者  阅读(224)  评论(0编辑  收藏  举报