Use the HTML5 Audio tag to synchronize the lyrics.

Source: Internet
Author: User

Use the HTML5 Audio tag to synchronize the lyrics.

HTML5 has been used for so long, but the audio tag in it has been used once. Of course, this tag is just inserted into the page. This time, I just helped my friends build several pages and use this audio tag to train my hands.

First, you need to insert an audio tag to the page. Note that loop = 'loop 'should not be set here. This attribute is used to set loop playback, this is because when the ended attribute needs to be used later, if the loop is set to loop, the ended attribute will always be false.

Autoplay = 'autoplay' sets the automatic playing of music after page loading. The preload and autoplay attributes play the same purpose. If the autoplay attribute appears in the tag, the preload attribute is ignored.

Controls = 'controls' sets the control bar for displaying music.

<Audio src = "music/Yesterday Once More.mp3" id = "aud" autoplay = "autoplay" controls = "controls" preload = "auto"> your browser does not support the audio attribute, change the browser to browse. </Audio>

With this tag, congratulations! You can play music on your page. But will this make the page seem 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 be selected. First, we need to download some lrc-format lyrics, and then you need to format these music. Because this is the first music file.

We need to insert each lyrics into a two-digit array. After formatting, the lyrics will become in this format.

The code for formatting the lyrics is attached here (of course the code here is used from somewhere else, the original http://www.cnblogs.com/Wayou/p/sync_lyric_with_html5_audio.html here)

// Function parseLyric (text) {// separates the text into one row and saves it to the array var lines = text. split ('\ n'), // The regular expression used to match the time. The matching result is similar to [xx: xx. xx] pattern =/\ [\ d {2 }:\ d {2 }. \ d {2} \]/g, // array for saving the final result = []; // remove the line without time while (! Pattern. test (lines [0]) {lines = lines. slice (1) ;}; // when '\ n' is used to generate an array, the last empty element in the result will be removed here. length-1]. length = 0 & lines. pop (); lines. forEach (function (v/* array element value */, I/* element index */, a/* array itself */) {// extract time [xx: xx. xx] var time = v. match (pattern), // extract the lyrics value = v. replace (pattern, ''); // because a row may have multiple times, the time may be [xx: xx. xx] [xx: xx. xx] [xx: xx. xx] format, which needs to be further separated by time. forEach (function (v1, i1, a1) {// remove the brackets in the time To get xx: xx. xx var t = v1.slice (1,-1 ). split (':'); // press the result into the final array result. push ([parseInt (t [0], 10) * 60 + parseFloat (t [1]), value]) ;}); // Finally, sort the elements in the result array by time, so that the result is displayed normally after saving. sort (function (a, B) {return a [0]-B [0];}); return result ;}

Here we can easily use the lyrics of each music. We need a function to get the lyrics and make them synchronously displayed on the page, switch the music normally. The code is attached below.

Function fn (sgname) {$. get ('music/'+ sgname + '. lrc ', function (data) {var str = parseLyric (data); for (var I = 0, li; I <str. length; I ++) {li =$ ('<li>' + str [I] [1] + '</li> '); $ ('# gc ul '). append (li) ;}$ ('# aud') [0]. ontimeupdate = function () {// triggers for (var I = 0, l = str. length; I <l; I ++) {if (this. currentTime/* Current playback time */> str [I] [0]) {// display to the page $ ('# gc ul'0000.css ('top ', -I * 40 + 200 + 'px '); // move the lyrics up $ (' # gc Ul li'{.css ('color', '# fff'); $ (' # gc ul li: nth-child('{(i1_1}'{'}.css ('color', 'red '); // highlight which lyrics are being played} if (this. ended) {// determine whether the current music has been played. var songslen = $ ('. songs_list li '). length; for (var I = 0, val; I <songslen; I ++) {val = $ ('. songs_list li: nth-child ('+ (I + 1) + ')'). text (); if (val = sgname) {I = (songslen-1 ))? 1: I + 2; sgname = $ ('. songs_list li: nth-child ('+ I + ')'). text (); // After the music is played, switch to the next Music $ ('# gc ul '). empty (); // clear the lyrics $ ('# aud '). attr ('src', 'music/'{sgname}'); fn (sgname); return ;}}}};});}
fn($('.songs_list li:nth-child(1)').text());

Now, your music lyrics can be normally displayed on the page. However, there is still something missing, that is, a music list. I want to click the music in this list to play the music. The code is attached below.

HTML code

<Div class = "songs_cnt"> <ul class = "songs_list"> <li> Yesterday Once More </li> <li> You Are Beautiful </li> </ul> <button class = "sel_song"> point <br/> mE </button> </div> <div id = "gc"> <ul> </ul> </div>

Css 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;        }

Js Code

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

Now, you have almost all the functions for synchronizing your lyrics. Today we are here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.