HTML5 video tag
HTML靜態頁面的使用↓
<!--影片未播放時的封面-->
<!--poster="images/60Orange.png"-->
<video src="content/movie.mp4"
controls
></video>
<!-- https://developers.google.com/web/updates/2017/09/autoplay-policy-changes -->
<!--必須同時設靜音才能自動播放影片-->
<!--autoplay
muted-->
Javascript 方式來控制影片播放↓
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="videoDir"></div>
<input type="button" value="play" id="button1" />
<script>
function createVideoElement(nameOfVideoFile) {
// Create a video object and set its properties.
var newVideo = document.createElement("video");
newVideo.src = nameOfVideoFile;
newVideo.loop = false;
newVideo.autoplay = false;
newVideo.controls = true;
newVideo.poster = "images/60banana.png";
// Add the video object to an existing element on the web page.
var hostElem = document.getElementById("videoDir");
hostElem.appendChild(newVideo);
var aVideo = newVideo;
document.getElementById("button1").onclick = function () {
if (aVideo.paused) {
console.log("Video current time: " + aVideo.currentTime + ", total duration: " + aVideo.duration);
aVideo.play();
}
else {
aVideo.pause();
}
};
aVideo.addEventListener("loadedmetadata", function () {
console.log("Video duration: " + aVideo.duration);
}, false);
// aVideo.addEventListener("loadeddata", function () {
// aVideo.play(); //Uncaught (in promise) DOMException
// }, false);
aVideo.addEventListener("timeupdate", function () {
console.log("Video current time: " + aVideo.currentTime);
}, false);
}
createVideoElement("content/movie.mp4");
</script>
</body>
</html>
另一個實務運用↓
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- https://developers.google.com/web/updates/2017/09/autoplay-policy-changes -->
<video id="video1" src="content/movie.mp4"
controls
poster="images/60Orange.png"
autoplay
muted
></video>
<script>
document.onvisibilitychange = function () {
if (document.visibilityState=="hidden") {//使用者點擊其他頁籤時,本頁visibilityState=="hidden"...
document.getElementById("video1").pause();//影片暫停,避免擾人
}else{
document.getElementById("video1").play();
}
};
</script>
</body>
</html>