在HTML5问世之前,要在网络上展示视频,音频,动画,除了使用第三方自主开发的播放器之外,使用得最多的工具就是Flash,但是需要在浏览器上安装各种插件,并且有时速度很慢。HTML5新增了两个与媒体相关的标签,让开发人员不必依赖任何插件就能在网页中嵌入跨浏览器的音频和视频内容,这两个标签是 < audio> 、< video>。
在页面中嵌入媒体元素:
<video src="resource/demo.mp4" type="video/mp4" controls autoplay></video>
- 通过source元素为同一个媒体数据指定多个播放格式与编码方式,确保浏览器可以从中选择一种自己支持的播放格式。
<video autoplay controls>
<source src="resource/demo_1.mp4" type="video/mp4">
<source src="resource/demo_2.mp4" type="video/mp4">
</video>
基本属性
属性 | 描述 |
---|
width | 视频的宽度,以像素为单位 |
Height | 视频的高度,以像素为单位 |
src | 视频的地址 |
controls | 控制条 |
autoplay | 设置自动播放 |
poster | 当视频不可用时,向用户展示一副替代用的图片 |
loop | 是否循环 |
volume | 音量,取值为0~1 |
muted | 是否处于静音状态 |
type | 媒体类型 MIME mp4- video/mp4 |
defaultPlaybackRate | 默认播放速率 |
playbackRate | 当前播放速率 |
currentTime | 当前播放位置 |
duration | 总的播放时间 |
只读属性
属性 | 描述 |
---|
currentSrc | 读取播放中的媒体数据的URL地址 |
readyState | 准备状态 |
played | 已经播放的时间段 |
paused | 是否暂停 |
ended | 是否播放完毕 |
共有方法
方法 | 描述 |
---|
play() | 播放媒体 |
pause() | 暂停播放 |
load() | 重新载入媒体进行播放 |
canPlayType() | 测试浏览器是否支持指定的媒体类型 |
各大浏览器对不同视频格式的支持程度:
浏览器 | MP4 | WebM | Ogg |
---|
Internet | Explorer | yes | no |
Chrome | yes | yes | yes |
Firefox | yes | yes | yes |
Safari | yes | no | no |
Opera | yes | yes | yes |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>video</title>
<script>
window.onload = function(){
var video = document.getElementsByTagName('video')[0]
var btnDiv = document.getElementsByClassName('btn_div')[0]
var toggle = document.getElementById('toggle')
document.onkeydown = function(event){
if(event.keyCode=='37'){
video.currentTime -=10;
}
if(event.keyCode=='39'){
video.currentTime +=10;
}
if(event.keyCode == '38'){
if(video.volume <1){
video.volume += 0.2
}
}
if(event.keyCode=='40'){
if(video.volume>0){
video.volume -=0.2
}
}
}
btnDiv.onclick=function(event){
var text = event.target.innerText
if(text == '播放'){
video.play()
}
if(text == '暂停'){
video.pause()
}
if(text =='快进'){
video.currentTime +=10;
}
if(text == '快退'){
video.currentTime -=10;
}
if(text == '快速播放'){
video.playbackRate = 2
}
if(text == '慢速播放'){
video.playbackRate = 0.5
}
}
toggle.onclick=function(event){
if(video.paused){
video.play()
this.innerText = '暂停'
}else{
video.pause()
this.innerText = '播放'
}
}
}
</script>
</head>
<body>
<video src="./image/a.mp4" width="400" height="400" controls autoplay loop></video>
<div class="btn_div">
<button>播放</button>
<button>暂停</button>
<button>快进</button>
<button>快退</button>
<button>快速播放</button>
<button>慢速播放</button>
</div>
<button id="toggle">播放</button>
</body>
</html>