bind(){ this.updateLine = () => { let percent = this.audio.buffered.length ? (this.audio.buffered.end(this.audio.buffered.length - 1) / this.audio.duration) : 0; this.dom.timeline_loaded.style.width = Util.percentFormat(percent); }; .audio.addEventListener('durationchange', (e) => { this.dom.timetext_total.innerHTML = Util.timeFormat(this.audio.duration); this.updateLine(); }); this.audio.addEventListener('progress', (e) => { this.updateLine(); }); this.audio.addEventListener('canplay', (e) => { if(this.option.autoplay && !this.isMobile){ this.play(); } }); this.audio.addEventListener('timeupdate', (e) => { let percent = this.audio.currentTime / this.audio.duration; this.dom.timeline_played.style.width = Util.percentFormat(percent); this.dom.timetext_played.innerHTML = Util.timeFormat(this.audio.currentTime); }); .audio.addEventListener('ended', (e) => { this.next(); }); this.dom.playbutton.addEventListener('click', this.toggle); this.dom.switchbutton.addEventListener('click', this.toggleList); if(!this.isMobile){ this.dom.volumebutton.addEventListener('click', this.toggleMute); } this.dom.modebutton.addEventListener('click', this.switchMode); this.dom.musiclist.addEventListener('click', (e) => { let target,index,curIndex; if(e.target.tagName.toUpperCase() === 'LI'){ target = e.target; }else{ target = e.target.parentElement; } index = parseInt(target.getAttribute('data-index')); curIndex = parseInt(this.dom.musiclist.querySelector('.skPlayer-curMusic').getAttribute('data-index')); if(index === curIndex){ this.play(); }else{ this.switchMusic(index + 1); } }); this.dom.timeline_total.addEventListener('click', (event) => { let e = event || window.event; let percent = (e.clientX - Util.leftDistance(this.dom.timeline_total)) / this.dom.timeline_total.clientWidth; if(!isNaN(this.audio.duration)){ this.dom.timeline_played.style.width = Util.percentFormat(percent); this.dom.timetext_played.innerHTML = Util.timeFormat(percent * this.audio.duration); this.audio.currentTime = percent * this.audio.duration; } }); if(!this.isMobile){ this.dom.volumeline_total.addEventListener('click', (event) => { let e = event || window.event; let percent = (e.clientX - Util.leftDistance(this.dom.volumeline_total)) / this.dom.volumeline_total.clientWidth; this.dom.volumeline_value.style.width = Util.percentFormat(percent); this.audio.volume = percent; if(this.audio.muted){ this.toggleMute(); } }); } }
View Code至此,核心代码基本完成,接下来就是自己根据需要完成API部分,详细部分移步至我的github查看源码。
最后我们暴露模块:
module.exports = skPlayer;
一个HTML5音乐播放器就大功告成了 ~ !