When a webpage plays audio, you can use jQuery and HTML to create a lyric scrolling effect. Here is a simple implementation:
HTML:
<div id="lyrics">
<p data-time="0:00.00">作词 : 娃娃</p>
<p data-time="0:01.00">作曲 : 陶喆</p>
<p data-time="0:04.50">Love... Baby LoveLoveLove baby</p>
<p data-time="0:12.78"></p>
<p data-time="0:24.76">请原谅我有决定会让你烦恼</p>
<p data-time="0:29.29">你要了解并不是你追得我想逃</p>
</div>
<audio id="audio" src="your-audio-file.mp3"></audio>jQuery:
$(document).ready(function() {
var audio = $("#audio")[0];
var lyricDiv = $("#lyrics");
audio.addEventListener("timeupdate", function() {
var currentTime = audio.currentTime;
var lyricP = lyricDiv.find("p");
lyricP.each(function() {
var lyricTime = $(this).data("time");
var lyricText = $(this).text();
if (currentTime >= convertToSeconds(lyricTime)) {
$(this).addClass("active").siblings().removeClass("active");
lyricDiv.animate({scrollTop: $(this).offset().top - lyricDiv.offset().top + lyricDiv.scrollTop() - 100}, 1000);
}
});
});
function convertToSeconds(time) {
var parts = time.split(":");
var minutes = parseInt(parts[0], 10);
var seconds = parseFloat(parts[1]);
return minutes * 60 + seconds;
}
});CSS:
#lyrics {
height: 400px;
overflow: auto;
text-align: center;
margin: 0 auto;
}
#lyrics p.active {
color: red;
}Explain the above code:
- First, add an element to each line of lyrics.
data-timeAttribute: Represents the time position in the audio file corresponding to this line of lyrics. - In the jQuery code, the value was retrieved.
audioThe location where elements and lyrics are situateddivElement; added one more.timeupdateEvent listener: This event is triggered whenever the audio playback time is updated. - In the event listener, first retrieve the current audio playback time, then iterate through each lyric line and determine whether that lyric line should be activated (i.e., whether it should be scrolled to the center of the screen). If so, add it.
activeClass, using jQueryanimateMethod: Scroll this line of lyrics to the center of the screen. - Finally, an auxiliary function is defined.
convertToSecondsUsed to convert a time string into seconds for comparison purposes.