1.引入js-base64對歌詞數(shù)據(jù)進行解碼
修改class Song類中的getLyric方法
this.lyric = Base64.decode(res.lyric)
Song類中的getLyric方法返回Promise對象實例
2.使用lyric-parser對歌詞進行解析
在player.vue中實現(xiàn)getLyric方法,得到經(jīng)過lyric-parser解析之后的歌詞。此方法調(diào)用Song類中的getLyric方法,得到返回的Promise對象實例。
getLyric() {
? ? ? ? this.currentSong.getLyric().then((lyric) => {
? ? ? ? ? ? ? ? // 經(jīng)過Lyric處理之后的currentLyric有屬性lines
? ? ? ? ? ? ? ?// lines[i] 有屬性time和txt,time是時間,txt是當前句子歌詞
? ? ? ? ? ? ? ?this.currentLyric = new Lyric(lyric, this.handleLyric)
? ? ? ? ? ? ? ?if (this.playing) {
? ? ? ? ? ? ? ? ? ? this.currentLyric.play()
? ? ? ? ? ? ? }
? ? ? ? ?}).catch(() => {
? ? ? ? ?})
}
調(diào)用this.currentLyric.play()方法時,進行歌詞播放,引起Lyric實例對象(這里是this.currentLyric)的lineNum改變。當lineNum改變時,觸發(fā)回調(diào)函數(shù)this.handleLyric。
在回調(diào)函數(shù)中,我們需要得到當前播放的歌詞行數(shù)(this.currentLineNum),并且實現(xiàn)歌詞面板的滾動(使用Scroll組件實現(xiàn)滾動),使當前播放的歌詞始終在屏幕中間位置。
handleLyric({lineNum, txt}) {
? ? ? ?// 當lineNum發(fā)生改變時,觸發(fā)handleLyric
? ? ? this.currentLineNum = lineNum
? ? ? if (lineNum > 5) {
? ? ? ? ? ? let lineEl = this.$refs.lyricLine[lineNum - 5]
? ? ? ? ? ?this.$refs.lyricList.scrollToElement(lineEl, 1000)
? ? ?} else {
? ? ? ? ? ?this.$refs.lyricList.scrollToElement(0, 0, 1000)
? ? }
}