< p >歌词同步滚动是网页上最常见的音频效果之一,它让用户可以更好地理解音乐内容。实现歌词同步滚动需要控制网页中显示的歌词,在音乐播放时根据音乐的到达时间滚动显示对应的歌词。下面是一个简单的HTML代码实现歌词同步滚动的示例:< /p >
< pre >
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>歌词同步滚动</title>
</head>
<body>
<div id="lyrics"></div>
<audio id="music" src="music.mp3" controls autoplay></audio>
<script>
var lyrics = [
{time: 0, text: "Verse 1"},
{time: 7, text: "I wish I found some better sounds no one's ever heard"},
{time: 12, text: "I wish I had a better voice that sang some better words"},
{time: 18, text: "I wish I found some chords in an order that is new"},
{time: 23, text: "I wish I didn't have to rhyme every time I sang"},
{time: 29, text: "I was told when I get older all my fears would shrink"},
{time: 34, text: "But now I'm insecure and I care what people think"}
];
function showLyrics() {
var time = music.currentTime;
var lyric = lyrics.find(function(item) {
return item.time >= time;
});
if (lyric) {
lyricsDiv.innerHTML = lyric.text;
}
}
var music = document.getElementById("music");
var lyricsDiv = document.getElementById("lyrics");
music.addEventListener("timeupdate", showLyrics);
</script>
</body>
</html>
< /pre >
< p >上面的代码中,我们定义了一个歌词数组,其中每个元素包含时间和歌词文本。使用JavaScript的find方法在歌曲播放时找到当前时间对应的歌词,并将其显示在网页中。我们将歌词放在一个id为"lyrics"的div中,在歌曲播放的过程中根据时间更新显示的歌词内容。每次歌曲时间改变都会触发一个timeupdate事件,利用这个事件可以实现歌词的同步滚动效果。通过上面的代码,我们可以快速实现一个简单的歌词同步滚动的效果,让用户更好地体验音乐。 < /p >