1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class LRCPlayer { constructor({ lyrics, print = (lyric) => console.log(lyric), done = () => { }, interval = 50 }) { this.lyrics = lyrics; this.print = print; this.done = done; this.interval = interval; this.seek = 0; this._timer = null; this.state = 'INIT'; }
play(seek = '00:00:00') { if (this.state === 'PLAY') return;
if (this.state !== 'PAUSE') { this.seek = toSecond(seek); } this.state = 'PLAY';
const lyrics = this.lyrics.map(lyric => [toSecond(lyric[0]), lyric[1]]).sort((lyric1, lyric2) => lyric1[0] - lyric2[0]).filter(lyric => lyric[0] >= this.seek); this._timer = setInterval(() => { if (lyrics.length === 0) { clearInterval(this._timer); this.done(); return; }
while (lyrics.length > 0 && lyrics[0][0] <= this.seek) this.print(lyrics.shift()[1]);
this.seek += (this.interval / 1000); }, this.interval); }
pause() { if (this.state === 'PAUSE') return; this.state = 'PAUSE'; clearInterval(this._timer); }
resume() { if (this.state === 'PAUSE') this.play(); }
reset() { this.pause(); this.state = 'INIT'; this.play(); } }
|