vue怎么实现歌词播放
Vue 实现歌词播放的方法
歌词解析与格式化 将歌词文件(如 LRC 格式)解析为结构化数据,通常转换为时间戳和歌词文本的数组。可以使用正则表达式匹配时间标签和歌词内容:
function parseLrc(lrcText) {
const lines = lrcText.split('\n')
return lines.map(line => {
const timeMatch = line.match(/\[(\d{2}):(\d{2})\.(\d{2,3})\]/)
if (!timeMatch) return null
const min = parseInt(timeMatch[1])
const sec = parseInt(timeMatch[2])
const ms = parseInt(timeMatch[3].padEnd(3, '0'))
const time = min * 60 + sec + ms / 1000
const text = line.replace(timeMatch[0], '').trim()
return { time, text }
}).filter(item => item)
}
音频播放与时间同步
使用 HTML5 Audio API 或第三方库(如 howler.js)播放音频,监听 timeupdate 事件获取当前播放时间:
data() {
return {
currentTime: 0,
audio: new Audio('audio.mp3')
}
},
mounted() {
this.audio.addEventListener('timeupdate', () => {
this.currentTime = this.audio.currentTime
})
}
歌词高亮与滚动 计算当前应该高亮显示的歌词行,并通过 CSS 实现高亮效果。使用 Vue 的响应式特性自动更新界面:
computed: {
currentLineIndex() {
if (!this.lrcData.length) return -1
for (let i = 0; i < this.lrcData.length; i++) {
if (this.currentTime < this.lrcData[i].time) {
return i - 1
}
}
return this.lrcData.length - 1
}
}
界面实现 在模板中渲染歌词列表,并通过动态类名实现高亮效果:
<div class="lyrics-container">
<div
v-for="(line, index) in lrcData"
:key="index"
:class="{ 'active': index === currentLineIndex }"
>
{{ line.text }}
</div>
</div>
样式优化 添加 CSS 实现平滑滚动和视觉效果:
.lyrics-container {
height: 300px;
overflow-y: auto;
scroll-behavior: smooth;
}
.lyrics-container div {
padding: 8px;
transition: all 0.3s;
}
.lyrics-container .active {
color: #42b983;
font-size: 1.2em;
font-weight: bold;
}
自动滚动功能 在歌词变化时自动滚动到当前行:
watch: {
currentLineIndex(newVal) {
const container = this.$el.querySelector('.lyrics-container')
const activeLine = container.children[newVal]
if (activeLine) {
container.scrollTop = activeLine.offsetTop - container.offsetHeight / 2
}
}
}
完整组件示例 将上述功能整合为一个可复用的 Vue 组件:
export default {
props: ['lrcText', 'audioSrc'],
data() {
return {
lrcData: [],
currentTime: 0,
audio: null
}
},
created() {
this.lrcData = this.parseLrc(this.lrcText)
this.audio = new Audio(this.audioSrc)
},
methods: {
parseLrc(lrcText) {
// 解析歌词的实现
}
},
// 其他选项如 computed, watch 等
}






