请求回来的歌词是以下格式
第一步先处理歌词
if (this.lyricList.lyric) { //判断有没有歌词,因为有些音乐没有歌词
arr = this.lyricList.lyric.split(/[(\f\n)\r\t\v]/).map((item, i) => { //用正则的换行符分割
let min = item.slice(1, 3);
let sec = item.slice(4, 6);
let mill = item.slice(7, 10);
let lrc = item.slice(11, item.length)
let time = parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill) //把分钟变成秒,秒变成毫秒
if (isNaN(Number(mill))) { //判断是不是数字 不是的话进行二次分割 有些还是这种格式的 53]
mill = item.slice(7, 9);
lrc = item.slice(10, item.length)
time = parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill) //把分钟变成秒,秒变成毫秒
}
return { min, sec, mill, lrc, time }
})
arr.forEach((item, i) => { //歌词到了最后一句的处理
if (i === arr.length - 1 || isNaN(arr[i + 1].time)) {
item.pre = 100000
} else { //没到最后一句 那么久等于下一句歌词的时间
item.pre = arr[i + 1].time
}
});
// console.log(arr);
return arr
}
数据处理后 打印arr数组就是这样的结构
然后进行渲染
<div class="musidLyric" ref="musidLyric" v-show="isLyricShow">
<p v-for="item in lyric" :key="item"
:class="{ active: currenTume * 1000 >= item.time && currenTume * 1000 < item.pre }">{{ item.lrc }}</p>
</div>
currenTume * 1000 >= item.time && currenTume * 1000 < item.pre
//这里判断的意思是歌曲播放的时长大于上一句歌词结束的时间 或者小于下一句歌词的时间 中间就是正在播放的歌词
//currenTume audio 里的属性
//pre 上句歌词的时间
//item 下句歌词的时间
监听然后就完事了
watch: {
currenTume(newValue) {
let p = document.querySelector('p.active') //获取这个p标签里的active
if (p) {
if (p.offsetTop > 300) {
this.$refs.musidLyric.scrollTop = p.offsetTop - 300 //如果p的高度超过了300 让父元素的可视高度等于 p元素超过的高减300 让父元素可视高在300内
}
}
if (newValue === this.duration) { //当前的时长等于总时长的时候 自动播放下一首
if (this.playListIndex === this.playList.length - 1) {
this.updatePlayListIndex(0);
this.play()
} else {
this.updatePlayListIndex(this.playListIndex + 1)
}
}
}
}