html5-声音视频自动播放的坑
因为从事的是教学软件的开发,不知何年何月开始声音、视频不支持自动播放了。必须点一个按钮才能播放。教学类软件很多都是有动画的,像播放器一样,从头开始慢慢播放,可以理解为n帧,但是因为程序开发不是视频制作,没有序列帧,所以要通过回调实现这些功能。经常开发这类软件,得寻找自己的方案。
果断选择了jquery,没错就是古老的jquery。直接对dom进行监听。哪个元素不能自动播放,我就在哪个元素上插个必须点击才能播放。
部分代码片段
var this_v=$(`#video_${this_id}`); this_v.attr("src",this_v.attr("xsrc")); var this_v_dom=document.getElementById(`video_${this_id}`); var this_c_dom=document.getElementById(`canvas_video_${this_id}`); this_c_dom.width = 1920; this_c_dom.height = 1080; var this_ctx=this_c_dom.getContext('2d'); var captureFrame=function() { // console.error('captureFrame'); // console.error(this_v_dom); // console.error(this_ctx); this_ctx.drawImage(this_v_dom, 0, 0, this_c_dom.width, this_c_dom.height); setTimeout(function(){ captureFrame(); },40); } try{ this_v_dom.play(); }catch(e){} var this_played=false; this_v_dom.addEventListener("ended",function(){ console.error("播放结束"); go_next(); }) this_v_dom.addEventListener("play",function(){ this_played=true; console.error('自动播放了'); captureFrame(); }) setTimeout(function(){ console.error('this_played',this_played); if(this_played==false) { //this_v_dom.muted=true; var dianji_html=`<div id="dianjipingmu">点击屏幕继续</div>`; $("#dianjipingmu").remove(); $(".app").eq(0).prepend(dianji_html); $("#dianjipingmu").click(function(){ $("#dianjipingmu").remove(); this_v.attr("src",this_v.attr("xsrc")); this_v_dom.play(); }); } },588);
野生办法,延迟判断一下是否播放成功。并监听是否播放结束,然后go_next();