Skip to content

多媒体

本章将介绍HTML5中的多媒体元素,包括视频、音频和嵌入内容。

视频元素

基本用法

<video> 标签用于在网页中嵌入视频内容:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频元素基本示例</title>
</head>
<body>
    <h2>基本视频播放</h2>
    
    <!-- 基本视频元素 -->
    <video src="video.mp4">
        您的浏览器不支持视频播放
    </video>
    
    <!-- 带控制器的视频 -->
    <video src="video.mp4" controls>
        您的浏览器不支持视频播放
    </video>
    
    <!-- 设置宽高 -->
    <video src="video.mp4" controls width="640" height="360">
        您的浏览器不支持视频播放
    </video>
</body>
</html>

video标签属性

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>video属性示例</title>
</head>
<body>
    <h2>视频属性演示</h2>
    
    <!-- 
        controls:显示播放控制器
        autoplay:自动播放(需要配合muted使用)
        muted:静音
        loop:循环播放
        poster:视频封面图
        preload:预加载策略
        width/height:视频尺寸
    -->
    <video 
        src="video.mp4"
        controls
        width="640"
        height="360"
        poster="cover.jpg"
        preload="auto"
        muted
        loop>
        您的浏览器不支持HTML5视频播放
    </video>
    
    <hr>
    
    <!-- 自动播放示例(静音才能自动播放) -->
    <h3>自动播放(静音)</h3>
    <video 
        src="background.mp4"
        autoplay
        muted
        loop
        width="640">
    </video>
</body>
</html>
属性说明
srcURL视频文件路径
controls布尔属性显示播放控制器
autoplay布尔属性自动播放(需配合muted)
muted布尔属性静音
loop布尔属性循环播放
posterURL视频封面图
preloadauto/metadata/none预加载策略
width像素值视频宽度
height像素值视频高度
playsinline布尔属性在iOS上内联播放

多格式视频源

为了兼容不同浏览器,可以提供多种视频格式:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多格式视频示例</title>
</head>
<body>
    <h2>多格式视频源</h2>
    
    <!-- 使用source标签提供多种格式 -->
    <video controls width="640" height="360">
        <!-- MP4格式(主流格式,兼容性最好) -->
        <source src="video.mp4" type="video/mp4">
        
        <!-- WebM格式(开源格式,压缩率高) -->
        <source src="video.webm" type="video/webm">
        
        <!-- Ogg格式(开源格式) -->
        <source src="video.ogg" type="video/ogg">
        
        <!-- 浏览器不支持时的提示 -->
        <p>您的浏览器不支持HTML5视频播放</p>
        <p>请<a href="video.mp4">点击下载</a>视频文件</p>
    </video>
</body>
</html>

视频格式对比

格式MIME类型特点浏览器支持
MP4video/mp4兼容性最好,主流格式所有主流浏览器
WebMvideo/webm开源免费,压缩率高Chrome、Firefox、Edge
Oggvideo/ogg开源免费Chrome、Firefox、Opera

视频API示例

使用JavaScript控制视频播放:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频API示例</title>
    <style>
        .video-container {
            max-width: 640px;
            margin: 0 auto;
        }
        .controls {
            margin-top: 10px;
        }
        button {
            padding: 8px 16px;
            margin-right: 5px;
            cursor: pointer;
        }
        .progress {
            width: 100%;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="video-container">
        <h2>自定义视频控制器</h2>
        
        <video id="myVideo" width="100%" poster="cover.jpg">
            <source src="video.mp4" type="video/mp4">
        </video>
        
        <!-- 进度条 -->
        <input type="range" id="progress" class="progress" value="0" min="0" max="100">
        
        <!-- 自定义控制按钮 -->
        <div class="controls">
            <button id="playBtn">播放</button>
            <button id="pauseBtn">暂停</button>
            <button id="stopBtn">停止</button>
            <button id="muteBtn">静音</button>
            <button id="fullBtn">全屏</button>
            
            <label>
                音量:
                <input type="range" id="volume" min="0" max="1" step="0.1" value="1">
            </label>
            
            <label>
                播放速度:
                <select id="speed">
                    <option value="0.5">0.5x</option>
                    <option value="1" selected>1x</option>
                    <option value="1.5">1.5x</option>
                    <option value="2">2x</option>
                </select>
            </label>
        </div>
        
        <p>当前时间:<span id="currentTime">0:00</span> / <span id="duration">0:00</span></p>
    </div>
    
    <script>
        // 获取视频元素
        const video = document.getElementById('myVideo');
        const progress = document.getElementById('progress');
        const volume = document.getElementById('volume');
        const speed = document.getElementById('speed');
        
        // 播放
        document.getElementById('playBtn').addEventListener('click', function() {
            video.play();
        });
        
        // 暂停
        document.getElementById('pauseBtn').addEventListener('click', function() {
            video.pause();
        });
        
        // 停止(暂停并回到开始)
        document.getElementById('stopBtn').addEventListener('click', function() {
            video.pause();
            video.currentTime = 0;
        });
        
        // 静音切换
        document.getElementById('muteBtn').addEventListener('click', function() {
            video.muted = !video.muted;
            this.textContent = video.muted ? '取消静音' : '静音';
        });
        
        // 全屏
        document.getElementById('fullBtn').addEventListener('click', function() {
            if (video.requestFullscreen) {
                video.requestFullscreen();
            }
        });
        
        // 音量控制
        volume.addEventListener('input', function() {
            video.volume = this.value;
        });
        
        // 播放速度
        speed.addEventListener('change', function() {
            video.playbackRate = this.value;
        });
        
        // 进度条控制
        progress.addEventListener('input', function() {
            const time = video.duration * (this.value / 100);
            video.currentTime = time;
        });
        
        // 视频时间更新
        video.addEventListener('timeupdate', function() {
            const value = (100 / video.duration) * video.currentTime;
            progress.value = value;
            
            // 更新时间显示
            document.getElementById('currentTime').textContent = formatTime(video.currentTime);
        });
        
        // 视频加载完成
        video.addEventListener('loadedmetadata', function() {
            document.getElementById('duration').textContent = formatTime(video.duration);
        });
        
        // 格式化时间
        function formatTime(seconds) {
            const min = Math.floor(seconds / 60);
            const sec = Math.floor(seconds % 60);
            return min + ':' + (sec < 10 ? '0' : '') + sec;
        }
    </script>
</body>
</html>

音频元素

基本用法

<audio> 标签用于在网页中嵌入音频内容:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>音频元素基本示例</title>
</head>
<body>
    <h2>基本音频播放</h2>
    
    <!-- 基本音频元素 -->
    <audio src="music.mp3">
        您的浏览器不支持音频播放
    </audio>
    
    <!-- 带控制器的音频 -->
    <audio src="music.mp3" controls>
        您的浏览器不支持音频播放
    </audio>
    
    <h3>带预加载的音频</h3>
    <audio src="music.mp3" controls preload="auto">
        您的浏览器不支持音频播放
    </audio>
</body>
</html>

audio标签属性

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>audio属性示例</title>
</head>
<body>
    <h2>音频属性演示</h2>
    
    <!-- 
        controls:显示播放控制器
        autoplay:自动播放(需要配合muted使用)
        muted:静音
        loop:循环播放
        preload:预加载策略
    -->
    <audio 
        src="music.mp3"
        controls
        preload="auto"
        loop>
        您的浏览器不支持HTML5音频播放
    </audio>
    
    <hr>
    
    <!-- 背景音乐(自动播放、循环、静音) -->
    <h3>背景音乐</h3>
    <audio 
        src="background.mp3"
        autoplay
        loop
        muted>
    </audio>
</body>
</html>
属性说明
srcURL音频文件路径
controls布尔属性显示播放控制器
autoplay布尔属性自动播放
muted布尔属性静音
loop布尔属性循环播放
preloadauto/metadata/none预加载策略

多格式音频源

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多格式音频示例</title>
</head>
<body>
    <h2>多格式音频源</h2>
    
    <audio controls>
        <!-- MP3格式(主流格式) -->
        <source src="music.mp3" type="audio/mpeg">
        
        <!-- WAV格式(无损音质) -->
        <source src="music.wav" type="audio/wav">
        
        <!-- Ogg格式(开源格式) -->
        <source src="music.ogg" type="audio/ogg">
        
        <!-- 浏览器不支持时的提示 -->
        <p>您的浏览器不支持HTML5音频播放</p>
    </audio>
</body>
</html>

音频格式对比

格式MIME类型特点浏览器支持
MP3audio/mpeg压缩率高,主流格式所有主流浏览器
WAVaudio/wav无损音质,文件大所有主流浏览器
Oggaudio/ogg开源免费Chrome、Firefox、Opera
AACaudio/aac高压缩率所有主流浏览器

音频播放列表

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>音频播放列表示例</title>
    <style>
        .player {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
            border-radius: 10px;
        }
        .playlist {
            list-style: none;
            padding: 0;
        }
        .playlist li {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #ddd;
        }
        .playlist li:hover {
            background: #e0e0e0;
        }
        .playlist li.active {
            background: #4CAF50;
            color: white;
        }
    </style>
</head>
<body>
    <div class="player">
        <h2>音乐播放器</h2>
        
        <audio id="audioPlayer" controls style="width: 100%;">
            <source src="" type="audio/mpeg">
        </audio>
        
        <h3>播放列表</h3>
        <ul class="playlist" id="playlist">
            <li data-src="song1.mp3">歌曲1 - 歌手A</li>
            <li data-src="song2.mp3">歌曲2 - 歌手B</li>
            <li data-src="song3.mp3">歌曲3 - 歌手C</li>
        </ul>
    </div>
    
    <script>
        const audio = document.getElementById('audioPlayer');
        const playlist = document.getElementById('playlist');
        const items = playlist.getElementsByTagName('li');
        
        // 点击播放列表项
        for (let item of items) {
            item.addEventListener('click', function() {
                // 移除其他项的active类
                for (let i of items) {
                    i.classList.remove('active');
                }
                
                // 添加active类
                this.classList.add('active');
                
                // 播放选中的歌曲
                audio.src = this.dataset.src;
                audio.play();
            });
        }
        
        // 自动播放下一首
        audio.addEventListener('ended', function() {
            const current = document.querySelector('.playlist li.active');
            const next = current.nextElementSibling;
            
            if (next) {
                next.click();
            }
        });
    </script>
</body>
</html>

嵌入内容

iframe嵌入

<iframe> 用于在当前页面中嵌入另一个HTML文档:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>iframe示例</title>
</head>
<body>
    <h2>iframe嵌入示例</h2>
    
    <!-- 基本iframe -->
    <iframe src="https://www.example.com" width="600" height="400"></iframe>
    
    <!-- 嵌入YouTube视频 -->
    <h3>嵌入YouTube视频</h3>
    <iframe 
        width="560" 
        height="315" 
        src="https://www.youtube.com/embed/VIDEO_ID" 
        frameborder="0" 
        allowfullscreen>
    </iframe>
    
    <!-- 嵌入地图 -->
    <h3>嵌入地图</h3>
    <iframe 
        src="https://www.google.com/maps/embed?pb=..." 
        width="600" 
        height="450" 
        style="border:0;" 
        allowfullscreen="">
    </iframe>
    
    <!-- sandbox安全限制 -->
    <h3>带安全限制的iframe</h3>
    <iframe 
        src="page.html" 
        sandbox="allow-scripts allow-same-origin">
    </iframe>
</body>
</html>

iframe属性

html
<iframe 
    src="page.html"           <!-- 嵌入页面地址 -->
    width="600"               <!-- 宽度 -->
    height="400"              <!-- 高度 -->
    name="myFrame"            <!-- 框架名称 -->
    frameborder="0"           <!-- 边框(0或1) -->
    scrolling="auto"          <!-- 滚动条(auto/yes/no) -->
    sandbox="allow-scripts"   <!-- 安全沙箱 -->
    allowfullscreen           <!-- 允许全屏 -->
    loading="lazy"            <!-- 懒加载 -->
>
</iframe>

sandbox属性值

说明
allow-scripts允许执行脚本
allow-same-origin允许同源访问
allow-forms允许表单提交
allow-popups允许弹出窗口
allow-top-navigation允许导航到顶级窗口
allow-downloads允许下载文件

embed和object

<embed><object> 用于嵌入外部内容(如Flash、PDF等):

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>embed和object示例</title>
</head>
<body>
    <h2>embed嵌入示例</h2>
    
    <!-- 嵌入PDF -->
    <embed src="document.pdf" type="application/pdf" width="600" height="400">
    
    <!-- 嵌入SVG -->
    <embed src="image.svg" type="image/svg+xml" width="200" height="200">
    
    <h2>object嵌入示例</h2>
    
    <!-- 嵌入PDF -->
    <object data="document.pdf" type="application/pdf" width="600" height="400">
        <p>您的浏览器不支持PDF显示,请<a href="document.pdf">下载查看</a></p>
    </object>
    
    <!-- 嵌入网页 -->
    <object data="page.html" type="text/html" width="600" height="400">
        <p>内容加载失败</p>
    </object>
</body>
</html>

canvas画布

<canvas> 用于绘制图形,需要配合JavaScript使用:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>canvas示例</title>
</head>
<body>
    <h2>Canvas画布示例</h2>
    
    <!-- 创建画布 -->
    <canvas id="myCanvas" width="400" height="300" style="border: 1px solid black;">
        您的浏览器不支持Canvas
    </canvas>
    
    <script>
        // 获取画布和绑定上下文
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');
        
        // 绘制矩形
        ctx.fillStyle = '#FF0000';        // 设置填充颜色
        ctx.fillRect(10, 10, 100, 80);    // 绘制填充矩形
        
        // 绘制边框矩形
        ctx.strokeStyle = '#0000FF';      // 设置边框颜色
        ctx.strokeRect(150, 10, 100, 80); // 绘制边框矩形
        
        // 绘制直线
        ctx.beginPath();
        ctx.moveTo(10, 120);              // 起点坐标
        ctx.lineTo(200, 120);             // 终点坐标
        ctx.stroke();                     // 绘制
        
        // 绘制圆形
        ctx.beginPath();
        ctx.arc(300, 150, 50, 0, 2 * Math.PI);  // 圆心坐标、半径、起始角度、结束角度
        ctx.fillStyle = '#00FF00';
        ctx.fill();
        
        // 绘制文字
        ctx.font = '20px Arial';
        ctx.fillStyle = '#000000';
        ctx.fillText('Hello Canvas', 10, 250);
        
        // 绘制渐变
        const gradient = ctx.createLinearGradient(150, 200, 350, 200);
        gradient.addColorStop(0, 'red');
        gradient.addColorStop(1, 'blue');
        ctx.fillStyle = gradient;
        ctx.fillRect(150, 200, 200, 50);
    </script>
</body>
</html>

SVG矢量图

SVG(Scalable Vector Graphics)是一种矢量图形格式:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>SVG示例</title>
</head>
<body>
    <h2>SVG矢量图示例</h2>
    
    <!-- 直接嵌入SVG代码 -->
    <svg width="400" height="300" style="border: 1px solid #ccc;">
        <!-- 矩形 -->
        <rect x="10" y="10" width="100" height="80" fill="#FF0000"/>
        
        <!-- 圆形 -->
        <circle cx="200" cy="60" r="50" fill="#00FF00"/>
        
        <!-- 椭圆 -->
        <ellipse cx="320" cy="60" rx="60" ry="40" fill="#0000FF"/>
        
        <!-- 直线 -->
        <line x1="10" y1="150" x2="200" y2="150" stroke="#000" stroke-width="2"/>
        
        <!-- 折线 -->
        <polyline points="10,200 50,180 100,220 150,180 200,200" 
                  fill="none" stroke="#FF00FF" stroke-width="2"/>
        
        <!-- 多边形 -->
        <polygon points="250,150 300,200 350,150 300,100" fill="#FFFF00"/>
        
        <!-- 文字 -->
        <text x="10" y="280" font-size="20" fill="#000">SVG矢量图形</text>
    </svg>
    
    <!-- 使用img标签引入SVG -->
    <h3>使用img引入</h3>
    <img src="image.svg" alt="SVG图片" width="200">
    
    <!-- 使用object引入SVG -->
    <h3>使用object引入</h3>
    <object data="image.svg" type="image/svg+xml" width="200"></object>
</body>
</html>

track字幕

<track> 标签用于为视频和音频添加字幕:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>track字幕示例</title>
</head>
<body>
    <h2>带字幕的视频</h2>
    
    <video controls width="640">
        <source src="video.mp4" type="video/mp4">
        
        <!-- 字幕轨道 -->
        <track 
            src="subtitles_zh.vtt"      <!-- 字幕文件路径 -->
            kind="subtitles"            <!-- 类型:subtitles/captions/descriptions/chapters/metadata -->
            srclang="zh"                <!-- 语言代码 -->
            label="中文字幕"            <!-- 显示标签 -->
            default>                    <!-- 默认启用 -->
        
        <!-- 英文字幕 -->
        <track 
            src="subtitles_en.vtt"
            kind="subtitles"
            srclang="en"
            label="English">
        
        您的浏览器不支持视频播放
    </video>
    
    <hr>
    
    <h2>VTT字幕文件格式示例</h2>
    <pre>
WEBVTT

00:00:01.000 --> 00:00:04.000
这是第一句字幕

00:00:05.000 --> 00:00:08.000
这是第二句字幕
可以有多行

00:00:09.000 --> 00:00:12.000
这是第三句字幕
    </pre>
</body>
</html>

track的kind属性

说明
subtitles字幕(翻译对话)
captions字幕(包含音效描述)
descriptions视频内容描述(用于屏幕阅读器)
chapters章节标题
metadata元数据

综合示例

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多媒体综合示例</title>
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f0f0;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .section {
            background: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .section h2 {
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
        }
        video, audio {
            width: 100%;
            max-width: 640px;
        }
        .video-container {
            position: relative;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
        }
        .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        canvas {
            display: block;
            margin: 10px auto;
            border: 1px solid #ccc;
        }
        svg {
            display: block;
            margin: 10px auto;
        }
    </style>
</head>
<body>
    <h1>HTML5多媒体元素</h1>
    
    <!-- 视频部分 -->
    <div class="section">
        <h2>视频播放</h2>
        <p>HTML5原生视频播放器,支持多种格式:</p>
        
        <video controls poster="https://picsum.photos/640/360">
            <source src="video.mp4" type="video/mp4">
            <source src="video.webm" type="video/webm">
            <track src="subtitles.vtt" kind="subtitles" srclang="zh" label="中文字幕" default>
            您的浏览器不支持HTML5视频播放
        </video>
        
        <p>提示:可以添加controls、autoplay、loop、muted等属性控制播放行为。</p>
    </div>
    
    <!-- 音频部分 -->
    <div class="section">
        <h2>音频播放</h2>
        <p>HTML5原生音频播放器:</p>
        
        <audio controls>
            <source src="music.mp3" type="audio/mpeg">
            <source src="music.ogg" type="audio/ogg">
            您的浏览器不支持HTML5音频播放
        </audio>
        
        <p>支持MP3、WAV、Ogg等格式。</p>
    </div>
    
    <!-- iframe嵌入 -->
    <div class="section">
        <h2>iframe嵌入</h2>
        <p>嵌入外部网页内容:</p>
        
        <iframe 
            src="https://www.example.com" 
            width="100%" 
            height="300"
            style="border: 1px solid #ccc;"
            loading="lazy"
            sandbox="allow-scripts allow-same-origin">
        </iframe>
    </div>
    
    <!-- Canvas画布 -->
    <div class="section">
        <h2>Canvas画布</h2>
        <p>使用JavaScript绑制图形:</p>
        
        <canvas id="demoCanvas" width="400" height="200">
            您的浏览器不支持Canvas
        </canvas>
        
        <script>
            const canvas = document.getElementById('demoCanvas');
            const ctx = canvas.getContext('2d');
            
            // 绘制彩色方块
            const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'];
            colors.forEach((color, i) => {
                ctx.fillStyle = color;
                ctx.fillRect(10 + i * 78, 10, 70, 70);
            });
            
            // 绘制圆形
            ctx.beginPath();
            ctx.arc(100, 150, 40, 0, 2 * Math.PI);
            ctx.fillStyle = '#E056FD';
            ctx.fill();
            
            // 绘制文字
            ctx.font = 'bold 16px Arial';
            ctx.fillStyle = '#333';
            ctx.fillText('Canvas 绘图示例', 180, 155);
        </script>
    </div>
    
    <!-- SVG矢量图 -->
    <div class="section">
        <h2>SVG矢量图</h2>
        <p>可缩放矢量图形,无损放大:</p>
        
        <svg width="400" height="100">
            <!-- 渐变定义 -->
            <defs>
                <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" style="stop-color:#FF6B6B;stop-opacity:1" />
                    <stop offset="100%" style="stop-color:#4ECDC4;stop-opacity:1" />
                </linearGradient>
            </defs>
            
            <!-- 渐变矩形 -->
            <rect x="10" y="10" width="380" height="80" rx="10" fill="url(#grad1)"/>
            
            <!-- 文字 -->
            <text x="200" y="60" font-size="24" fill="white" text-anchor="middle" font-weight="bold">
                SVG 矢量图形
            </text>
        </svg>
        
        <p>SVG是基于XML的矢量图形格式,可以无限缩放而不失真。</p>
    </div>
</body>
</html>

本章小结

本章我们学习了:

  1. 视频元素<video> 标签及其属性,多格式视频源
  2. 音频元素<audio> 标签及其属性,多格式音频源
  3. 嵌入内容<iframe><embed><object>
  4. Canvas画布:使用JavaScript绑制图形
  5. SVG矢量图:可缩放矢量图形
  6. track字幕:为视频添加字幕

下一章

下一章我们将学习 语义化,了解HTML5的语义化标签及其重要性。