给原来的MP3测试网页添加了跳过片头片尾功能,现记录如下:
1、localStorage能够用久存储信息,比cookie好用,js直接可以调用(localStorage.name或localStorage[name]),键名无需引号
localStorage.record=rec.record
localStorage.folder=rec.folder
localStorage.file=rec.file
2、用json数据方式上传至后台,后台php解析起来比较清晰,注意:post不能直接上传json数据,先要用js(JSON.stringify(historyMessage))转成json字符串,后台php(json_decode($old_content,true))可以直接将字符串保存,或者解析后再修改数据
js上传json数据
// 获取历史记录
localStorage.record=vObj.currentTime;
historyMessage={folder:localStorage.folder,file:localStorage.file,record:localStorage.record};
historyMessage=JSON.stringify(historyMessage);
// 发送历史记录
var xml=new XMLHttpRequest();
xml.open("POST",location.href,true);
xml.setRequestHeader("Content-type", "application/json");
xml.setRequestHeader("kbn-version", "5.3.0");
xml.send(historyMessage);
php接收数据
if(empty($_POST)){
$content=file_get_contents('php://input');
// 如果记录文件为空或者文件不存在就直接新建一个文件
if(file_exists($_path)==false||filesize($_path)==0){
$_file=fopen($_path, 'w');
$newcontent=array();
array_push($newcontent, $content);//数组追加竟然不需要重新赋值???返回值是数据“1”
$newcontent=json_encode($newcontent);
fwrite($_file,$newcontent);
fclose($_file);
}else{
//打开文件 只读不写,php写文件的方式有点奇怪,修改文件好像只能先读后写,打开两次
$_file=fopen($_path, 'r');
$old_content=fread($_file,filesize($_path));
fclose($_file);
//将读取的json数据转换成数组
$old_content=json_decode($old_content,true);
//如果数组的数量达到10,则删除第一个数组,不让历史记录超出十个
if(count($old_content)==10){
array_shift($old_content);
}
//将接受的数据添加到数组
array_push($old_content, $content);
//将获得的新数组再次转换成json数据
$old_content=json_encode($old_content);
//重新以‘w’方式打开文件,将文件写回————这里踩了坑!!!!!!
$_file=fopen($_path, 'w');
fwrite($_file,$old_content);
fclose($_file);
}
}
3、设定跳过片头片尾,跳过片头比较简单,直接用currenttime即可
vObj.addEventListener('play', function () {
// 如果当前时间小于jumphead时间,则当前时间为jumphead时间
if (this.currentTime<parseInt(localStorage.jumphead)){
this.currentTime=parseInt(localStorage.jumphead)
}
}, false);
4、跳过片尾比较麻烦,用timeupdate事件比较简单,但会频繁刷currenttim,改用定时器,播放时计算剩余时间,然后定时跳转,但这样播放暂停,和进度跳转都会有麻烦,最后还是用tiimeupdate,一句话了事
vObj.addEventListener('timeupdate', function () {
if(this.duration-this.currentTime-localStorage.jumpend<=0){
nextClick(1)
}
}, false);
这里学到了audio的几个事件,记录一下
onbeforunlod事件,浏览器退出前执行的事件
//onbeforunlod事件,浏览器退出前执行的事件
window.onbeforeunload= function (e) {//为什么非要传参数e 奇怪???????
// localStorage.record=vObj.currentTime;
// }
数据加载好是执行的事件,这个事件加载好才有this.duration即数据的长度
//数据加载好是执行的事件,这个事件加载好才有this.duration即数据的长度
vObj.addEventListener('loadedmetadata', function () {
// jumpend();
// // console.log(this.duration);
// }, false);
播放事件,点击播放按钮时启动事件
vObj.addEventListener('play', function () {
// 如果当前时间小于jumphead时间,则当前时间为jumphead时间
if (this.currentTime<parseInt(localStorage.jumphead)){
this.currentTime=parseInt(localStorage.jumphead)
}
}, false);
暂停事件,暂停时触发事件
vObj.addEventListener('pause', function () {
localStorage.record=vObj.currentTime;
}, false);
结束事件,媒体播放结束
vObj.addEventListener('ended', function () {
nextClick(1);
}, false);