自定义样式
audio和vedio是默认看不见元素的,可以使用设置controls样式使其可见(该样式由浏览器自己提供),在network中看到media看到相关的信息。这里我们取消controls自定义它的样式。
<div class="box">
<video id="myVideo">
<source src="http://www.w3school.com.cn/i/movie.ogg" muted>
</video>
<div>
<button id="switch">播放/暂停</button>
<span id="current">0:00</span>/<span id="duration">0.00</span>
</div>
</div>
<script>
var myVideo = document.getElementById('myVideo');
document.getElementById('switch').onclick = function () {
if (myVideo.paused) {
myVideo.play();
} else {
myVideo.pause();
}
}
// 得到音频时间
myVideo.oncanplay = function () {
var m = Math.floor(myVideo.duration / 60);
var s = parseInt(myVideo.duration % 60);
s = s < 10 ? '0' + s : 's';
document.getElementById('duration').innerHTML = m + ':' + s;
}
// 监听音频播放时间
myVideo.ontimeupdate = function () {
var time = myVideo.currentTime;
var m = Math.floor(time / 60);
var s = parseInt(time % 60);
s = s < 10 ? '0' + s : 's';
document.getElementById('current').innerHTML = m + ':' + s;
}
</script>
更多属性与事件请参考 属性与事件
audio.html:26 Uncaught (in promise) DOMException报错
Chrome的自动播放的政策在2018年4月做了更改,当有用户行为发生时才会触发(click,tap)。
兼容
浏览器自动匹配支持的格式
<audio controls>
<source src="http://www.w3school.com.cn/i/movie.ogg"/>
<source src="http://www.w3school.com.cn/i/movie.mp3"/>
<source src="http://www.w3school.com.cn/i/movie.wav"/>
</audio>