H5 兩個video視頻的無縫切換

在網上找了好多方法都不知所以然,試了很多方法都無法做到中間不閃爍無縫切換,最終自己想到了一個方案。

原理是先將video標籤overflow: hidden;(不能使用display:none;會被禁止預載播放),讓第二個視頻play()後在canplay事件裏暫停自身,然後播放第一個視頻,第一個視頻播放結束事件ended裏執行第二個視頻的播放,以此做到無縫切換。

方法是不是很另類,不過倒是解決問題了,切換不會閃爍了,缺點可能就是兩個視頻一起緩衝了吧,不知有沒有大神有更好的解決方案?

<!DOCTYPE html>
<html lang="zh-cn">
<head>
	<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0">
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta charset="UTF-8">
	<title>視頻交互</title>

	<style type="text/css">

		/*視頻*/
		#video_box{position: fixed;left: 0;top: 0;width: 100%;height: 100%;overflow: hidden;}
		#video_box video{
			display: block; margin: 0 auto; width: 100%;height: 100%; /*object-fit:fill;*/
			position: absolute;left: 0;top: 0;visibility: hidden;
		}

	</style>
</head>
<body>
	<!-- 視頻播放區 -->
	<div id="video_box">
		<video id="vplayer_start" src="images/bg1.mp4" autoplay="false" webkit-playsinline="true" playsinline="true" x-webkit-airplay="allow" x5-video-player-type="h5" x5-video-player-fullscreen="true" x5-video-orientation="portraint" style="object-fit:fill"></video>
		<video id="vplayer" src="images/bg2.mp4" autoplay="false" webkit-playsinline="true" playsinline="true" x-webkit-airplay="allow" x5-video-player-type="h5" x5-video-player-fullscreen="true" x5-video-orientation="portraint" style="object-fit:fill;"></video>
	</div>


	<script>

		var startPlay=true;
		var vplayer_start = document.getElementById('vplayer_start');
		var vplayer = document.getElementById('vplayer'),
		video_box = document.getElementById('video_box');

		vplayer_start.pause();
		vplayer.play();
		// 播放結束
		vplayer_start.addEventListener("ended",function(e){
			vplayer.style.visibility = "visible";
			vplayer.play();
			e.target.style.display = "none";
		});
        //循環播放第二個視頻
		vplayer.addEventListener("ended",function(e){
			e.target.play();
		});

		vplayer.addEventListener('canplay', function(e){
			if(startPlay){
				e.target.pause();
				vplayer_start.style.visibility = "visible";
				vplayer_start.play();
				startPlay=false;
			}
		})


	</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章