B站加速脚本原理
可以参见我的上一篇文章(内含源码)学习利器,借助Tampermonkey写一个B站视频加速器脚本
JavaScript控制视频的播放速度,使用下面代码:
var vd = document.getElementsByTagName("video");
vd[0].playbackRate =s;
使用此方法的确可以增加速度,但是如果观看多集的视频会发现,每当加载新的视频就会失效,但是B站上面设置的速度可以在加载新的视频而视频的播放速度不重新变为1倍速
研究B站的本地存储发现:
B站使用了会话存储存放视频的播放速度,键为bilibili_player_settings,值为
{"block":{"status":true,"aiblock":true,"ailevel":3,"type_scroll":true,"type_top":true,"type_bottom":true,"type_reverse":true,"type_guest":true,"type_color":true,"function_normal":true,"function_subtitle":true,"function_special":true,"cloud_level":2,"cloud_source_video":true,"cloud_source_partition":true,"cloud_source_all":true,"size":0,"regexp":false,"dmChecked":true,"list":[]},
"video_status":{"videoaid":"20448584","videobvid":"BV1pW411W7kk","videospeed":1}
}
可以看出在video_status的videospeed为1,这个值就是播放的速度,每次加载新的视频时会读取videospeed的值然后设置播放的值为此值。
通过sessionStorage获取信息后发现是字符串类型
var str = sessionStorage.getItem("bilibili_player_settings");
有两种解决方案1.匹配字符串更改数值 2.转化JSON对象更改数值。
方案1:使用字符串匹配不容易匹配要使用正则,但是当第一次打开视频没有点击视频加速按钮时,就会发现会话存储没有videospeed,这就增加了难度
方案2:可以使用
var j = JSON.parse(str);
转换为JSON对象,可以添加属性和更改属性的值。
最后设计一个小按钮可以点击加速,可以灵活的设置速度,外加设置z-index的值来实现网页全屏还可以显示点击按钮。
var sped = document.createElement("div");
sped.innerText = "1X";
sped.style.position = "fixed";
sped.style.backgroundColor = "rgba(253, 102, 1, 0.5)";
sped.style.width = "60px";
sped.style.height = "100px";
sped.style.top = "250px";
sped.style.right = "0px";
sped.style.borderRadius = "15px 0px 0px 15px";
sped.style.fontSize = "24px";
sped.style.display = "flex";
sped.style.alignItems = "center";
sped.style.justifyContent = "center";
sped.style.userSelect = "none";
sped.style.zindex = 99999999;
document.body.appendChild(sped);
$(sped).css({"z-index":99999999})