最近在做一個項目,要求監控視頻的播放事件並能夠打印LOG日志,經過一番思索,使用javascript實現了此功能,代碼如下:
HTML:
復制代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Multi Source</title>
</head>
<body>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
<video src="http://www.w3school.com.cn/i/movie.mp4" controls autoplay></video>
</body>
</html>
JS:
復制代碼 代碼如下:
<script type="text/javascript">
window.addEventListener("load",getVideoEvent);
function getVideoEvent(){
var videoes=document.getElementsByTagName("video");
for (var i = 0; i < videoes.length; i++) {
showEventLog("video"+(i+1),videoes[i]);
}
}
function showEventLog(videoNum,Media){
eventTester = function(e){
Media.addEventListener(e,function(){
console.log(videoNum+":"+e);
});
}
eventTester("loadstart"); //客戶端開始請求數據
eventTester("progress"); //客戶端正在請求數據
eventTester("suspend"); //延遲下載
eventTester("abort"); //客戶端主動終止下載(不是因為錯誤引起),
eventTester("error"); //請求數據時遇到錯誤
eventTester("stalled"); //網速失速
eventTester("play"); //play()和autoplay開始播放時觸發
eventTester("pause"); //pause()觸發
eventTester("loadedmetadata"); //成功獲取資源長度
eventTester("loadeddata"); //
eventTester("waiting"); //等待數據,並非錯誤
eventTester("playing"); //開始回放
eventTester("canplay"); //可以播放,但中途可能因為加載而暫停
eventTester("canplaythrough"); //可以播放,歌曲全部加載完畢
eventTester("seeking"); //尋找中
eventTester("seeked"); //尋找完畢
eventTester("timeupdate"); //播放時間改變
eventTester("ended"); //播放結束
eventTester("ratechange"); //播放速率改變
eventTester("durationchange"); //資源長度改變
eventTester("volumechange"); //音量改變
}
</script>
小伙伴們主要看下本文的思路即可,希望對大家能有所幫助