search
HomeWeb Front-endH5 TutorialDetailed introduction to the effect of HTML5 using Audio tags to achieve lyrics synchronization

The most powerful thing about

HTML5 is the processing of media files. For example, using a simple vedio tag can realize video playback. Similarly, there is a corresponding tag for processing audio files in HTML5, that is, the audio tag. Through this article, I will introduce to you the effect of HTML5 using the Audio tag to achieve lyrics synchronization. Friends who are interested can learn together. The most powerful thing about HTML5 is the processing of media files. For example, video playback can be achieved by using a simple vedio tag. Similarly, there are corresponding tags for processing audio files in HTML5, that is, the audio tag
HTML5 has been out for so long, but the audio tag in it has only been used once. Of course, it is just to insert this tag. to the page. This time I just took advantage of helping a friend to create a few pages and practice using the audio tag.
First you need to insert an audio tag into the page. Note that it is best not to set loop='loop' here. This attribute is used to set the loop playback, because it will be played later. When you need to use the ended attribute, if loop is set to loop, the ended attribute will always be false.
autoplay='autoplay'Set to automatically play music after the page is loaded. The preload and autoplay attributes have the same effect. If the autoplay attribute appears in the tag, the preload attribute will be ignored.
controls='controls'Set the control bar for displaying music.

XML/HTML Code复制内容到剪贴板
<audio src="music/Yesterday Once More.mp3" id="aud" autoplay="autoplay" controls="controls" preload="auto">
您的浏览器不支持audio属性,请更换浏览器在进行浏览。    
</audio>

After you have this tag, congratulations, your page can already play music. But this would make the page too monotonous, so I added some things to the page so that the lyrics can be displayed on the page synchronously and the music to be played can also be selected. So first to achieve this effect, we have to download some lyrics files in lrc format, and then you need to format the music. Because the initial music file is like this

Detailed introduction to the effect of HTML5 using Audio tags to achieve lyrics synchronization


We need to insert each lyric into a two-digit array and format it After that, the lyrics will become in this format
Attached here is the code for formatting the lyrics

Detailed introduction to the effect of HTML5 using Audio tags to achieve lyrics synchronization


##

XML/HTML Code复制内容到剪贴板
//歌词同步部分    
function parseLyric(text) {    
//将文本分隔成一行一行,存入数组    
var lines = text.split(&#39;\n&#39;),    
//用于匹配时间的正则表达式,匹配的结果类似[xx:xx.xx]    
pattern = /\[\d{2}:\d{2}.\d{2}\]/g,    
//保存最终结果的数组    
result = [];    
//去掉不含时间的行    
while (!pattern.test(lines[0])) {    
lineslines = lines.slice(1);    
};    
//上面用&#39;\n&#39;生成生成数组时,结果中最后一个为空元素,这里将去掉    
lines[lines.length - 1].length === 0 && lines.pop();    
lines.forEach(function(v /*数组元素值*/ , i /*元素索引*/ , a /*数组本身*/ ) {    
//提取出时间[xx:xx.xx]    
var time = v.match(pattern),    
//提取歌词    
vvalue = v.replace(pattern, &#39;&#39;);    
//因为一行里面可能有多个时间,所以time有可能是[xx:xx.xx][xx:xx.xx][xx:xx.xx]的形式,需要进一步分隔    
time.forEach(function(v1, i1, a1) {    
//去掉时间里的中括号得到xx:xx.xx    
var t = v1.slice(1, -1).split(&#39;:&#39;);    
//将结果压入最终数组    
result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);    
});    
});    
//最后将结果数组中的元素按时间大小排序,以便保存之后正常显示歌词    
result.sort(function(a, b) {    
return a[0] - b[0];    
});    
return result;    
}

When we get here we can It is easy to use the lyrics of each piece of music. We need to have a function to obtain the lyrics and display them on the page synchronously, so that the music can be switched normally. The code is attached below.

XML/HTML Code复制内容到剪贴板
function fn(sgname){    
$.get(&#39;music/&#39;+sgname+&#39;.lrc&#39;,function(data){    
var str=parseLyric(data);    
for(var i=0,li;i<str.length;i++){    
li=$(&#39;<li>&#39;+str[i][1]+&#39;</li>&#39;);    
$(&#39;#gc ul&#39;).append(li);    
}    
$(&#39;#aud&#39;)[0].ontimeupdate=function(){//视屏 音频当前的播放位置发生改变时触发    
for (var i = 0, l = str.length; i < l; i++) {    
if (this.currentTime /*当前播放的时间*/ > str[i][0]) {    
//显示到页面    
$(&#39;#gc ul&#39;).css(&#39;top&#39;,-i*40+200+&#39;px&#39;); //让歌词向上移动    
$(&#39;#gc ul li&#39;).css(&#39;color&#39;,&#39;#fff&#39;);    
$(&#39;#gc ul li:nth-child(&#39;+(i+1)+&#39;)&#39;).css(&#39;color&#39;,&#39;red&#39;); //高亮显示当前播放的哪一句歌词    
}    
}    
if(this.ended){ //判断当前播放的音乐是否播放完毕    
var songslen=$(&#39;.songs_list li&#39;).length;    
for(var i= 0,val;i<songslen;i++){    
val=$(&#39;.songs_list li:nth-child(&#39;+(i+1)+&#39;)&#39;).text();    
if(val==sgname){    
i=(i==(songslen-1))?1:i+2;    
sgname=$(&#39;.songs_list li:nth-child(&#39;+i+&#39;)&#39;).text(); //音乐播放完毕之后切换下一首音乐    
$(&#39;#gc ul&#39;).empty(); //清空歌词    
$(&#39;#aud&#39;).attr(&#39;src&#39;,&#39;music/&#39;+sgname+&#39;.mp3&#39;);    
fn(sgname);    
return;    
}    
}    
}    
};    
});    
} fn($(&#39;.songs_list li:nth-child(1)&#39;).text());

So now your music lyrics can be displayed on the page normally and synchronously. But there is still one thing missing, which is a list of music. I hope to be able to click on the music in this list to play the music. The code is attached below.


HTML code

XML/HTML Code复制内容到剪贴板
<p class="songs_cnt">
<ul class="songs_list">
<li>Yesterday Once More</li>
<li>You Are Beautiful</li>
</ul>
<button class="sel_song">点<br/><br/>我</button>
</p>
<p id="gc">
<ul></ul>
</p>

css code

XML/HTML Code复制内容到剪贴板
#gc{    
width: 400px;    
height: 400px;    
background: transparent;    
margin: 100px auto;    
color: #fff;    
font-size: 18px;    
overflow: hidden;    
position: relative;    
}    
#gc ul{    
position: absolute;    
top: 200px;    
}    
#gc ul li{    
text-align: center;    
height: 40px;    
line-height: 40px;    
}    
.songs_cnt{    
float: left;    
margin-top: 200px;    
position: relative;    
}    
.songs_list{    
background-color: rgba(0,0,0,.2);    
border-radius: 5px;    
float: left;    
width: 250px;    
padding: 15px;    
margin-left: -280px;    
}    
.songs_list li{    
height: 40px;    
line-height: 40px;    
font-size: 16px;    
color: rgba(255,255,255,.8);    
cursor: pointer;    
}    
.songs_list li:hover{    
font-size: 20px;    
color: rgba(255,23,140,.6);    
}    
.sel_song{    
position: absolute;    
top: 50%;    
width: 40px;    
height: 80px;    
margin-top: -40px;    
font-size: 16px;    
text-align: center;    
background-color: transparent;    
border: 1px solid #2DCB70;    
font-weight: bold;    
cursor: pointer;    
border-radius: 3px;    
font-family: sans-serif;    
transition:all 2s;    
-moz-transition:all 2s;    
-webkit-transition:all 2s;    
-o-transition:all 2s;    
}    
.sel_song:hover{    
color: #fff;    
background-color: #2DCB70;    
}    
.songs_list li.active{    
color: #f00;    
}

jscode

XML/HTML Code复制内容到剪贴板
$(&#39;.songs_list li:nth-child(1)&#39;).addClass(&#39;active&#39;);    
$(&#39;.songs_cnt&#39;).mouseenter(function () {    
var e=event||window.event;    
var tag= e.target||e.srcElement;    
if(tag.nodeName==&#39;BUTTON&#39;){    
$(&#39;.songs_list&#39;).animate({&#39;marginLeft&#39;:&#39;0px&#39;},&#39;slow&#39;);    
}    
});    
$(&#39;.songs_cnt&#39;).mouseleave(function () {    
$(&#39;.songs_list&#39;).animate({&#39;marginLeft&#39;:&#39;-280px&#39;},&#39;slow&#39;);    
});    
$(&#39;.songs_list li&#39;).each(function () {    
$(this).click(function () {    
$(&#39;#aud&#39;).attr(&#39;src&#39;,&#39;music/&#39;+$(this).text()+&#39;.mp3&#39;);    
$(&#39;#gc ul&#39;).empty();    
fn($(this).text());    
$(&#39;.songs_list li&#39;).removeClass(&#39;active&#39;);    
$(this).addClass(&#39;active&#39;);    
});    
})

The above is the detailed content of Detailed introduction to the effect of HTML5 using Audio tags to achieve lyrics synchronization. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool