JS: 检测不同系统/浏览器所支持的视频格式+回退操作
  • 今天写页面发现一个问题,不同浏览器之间的视频播放器需要做好适配,记录一下检测和自动切换的办法。
  • 将下方HTML自行部署到服务器,从不同设备和浏览器测试,可以发现差异还是不小的。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频格式检测与切换示例</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        .container {
            text-align: center;
        }
        #videoPlayer {
            width: 640px;
            margin-bottom: 10px;
        }
        #formatInfo {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <video id="videoPlayer" controls width="640">
            <source id="videoSource" src="video.mp4" type="video/mp4">
            您的浏览器不支持视频播放。
        </video>
        <div id="formatInfo">当前格式: MP4</div>
        <button id="switchFormat">切换格式</button>
    </div>
    <script>
        const supportedFormats = {
            'mp4': 'video/mp4',
            'webm': 'video/webm',
            'ogg': 'video/ogg'
        };
        const videoPlayer = document.getElementById('videoPlayer');
        const videoSource = document.getElementById('videoSource');
        const switchFormatButton = document.getElementById('switchFormat');
        const formatInfo = document.getElementById('formatInfo');

        function checkSupportedFormats() {
            const video = document.createElement('video');
            const supportedList = [];
            Object.keys(supportedFormats).forEach(format => {
                if (video.canPlayType(supportedFormats[format]) !== '') {
                    supportedList.push(format);
                }
            });
            if (supportedList.length > 0) {
                formatInfo.innerHTML = `支持的视频格式: ${supportedList.join(', ')}`;
            } else {
                formatInfo.innerHTML = '没有检测到支持的视频格式。';
            }
        }

        function switchVideoFormat() {
            const formats = Object.keys(supportedFormats);
            let currentFormatIndex = formats.indexOf(videoSource.src.split('.').pop());
            currentFormatIndex = (currentFormatIndex + 1) % formats.length;
            const nextFormat = formats[currentFormatIndex];
            videoSource.src = `video.${nextFormat}`;
            videoSource.type = supportedFormats[nextFormat];
            videoPlayer.load();
            videoPlayer.play();
            formatInfo.innerHTML = `当前格式: ${nextFormat.toUpperCase()}`;
        }

        switchFormatButton.addEventListener('click', switchVideoFormat);

        window.onload = checkSupportedFormats;
    </script>
</body>
</html>
暂无评论

发送评论 编辑评论


				
上一篇
下一篇