// 0) {
this.lrcArr.push(item);
}
}
frag = document.createDocumentFragment();
for(i = 0,len = this.lrcArr.length; i < len; i++) {
var li = cEl('li');
if(i === 0) {
li.className = 'cur';
}
li.innerHTML = this.lrcArr[i].replace(/\[.+\]/i,'')
.replace('// ]]>','').replace('//','');
//处理时间
this.timestamp.push(this.lrcArr[i].replace(re,function(a,b,c) {
return b;
}).replace('[','').replace(']',''));
frag.appendChild(li);
}
ul.appendChild(frag);
this.li = g('lrcArea').getElementsByTagName('li');
},
//播放
play:function() {
this.stop = false;
var that = this,
player = this.player,
i,len;
this.t = setInterval(function() {
if(that.stop) return;
that.curTime = player.currentTime;
for(i = 0,len = that.timestamp.length - 1; i < len; i++) {
var prevTime = that.formatTimeStamp( that.timestamp[i] ),
nextTime = that.formatTimeStamp( that.timestamp[i + 1] );
//当前播放时间与前后歌词时间比较,如果位于这两者之间则转到该歌词
if( parseFloat( that.curTime ) > prevTime && parseFloat( that.curTime ) < nextTime ) {
that.scrollToLrc(i);
return;
}
}
},300);
},
//暂停
pause:function() {
this.stop = true;
clearInterval(this.t);
},
//格式化时间
formatTimeStamp:function(timestamp) {
var re = /([0-9]+):([0-9]+)\.([0-9]+)/i,
seconds = timestamp.replace(re,function(a,b,c,d) {
return Number(b * 60) + Number(c) + parseFloat('0.'+ d);
});
return seconds;
},
//歌词滚动
scrollToLrc:function(idx) {
var ds = getOffset(this.li[idx]).top,
i,len;
//如果歌词索引没有变动,则认为这句没有唱完,不处理
if(this.idx === idx) return;
//否则更新索引值并更新样式和位置
this.idx = idx;
for(i = 0,len = this.li.length; i < len; i++) {
this.li[i].className = '';
}
this.li[idx].className = 'cur';
this.lrcArea.scrollTop = ds - this.lrcArea.offsetHeight / 2;
}
};
function g(id) {
return typeof id === 'string' ? document.getElementById(id) : id;
}
function cEl(el) {
return document.createElement(el);
}
function trim(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function isEmptyObj(o) {
for(var p in o) return false;
return true;
}
function getOffset(el) {
var parent = el.offsetParent,
left = el.offsetLeft,
top = el.offsetTop;
while(parent !== null) {
left += parent.offsetLeft;
top += parent.offsetTop;
parent = parent.offsetParent;
}
return {
left: left,
top: top
};
}
var p = new musicPlayer({
player: g('player'),
lrc: g('lrc').innerHTML,
lrcArea: g('lrcArea')
});
// ]]>