HTML5 fantastic journey

Source: Internet
Author: User
Tags api manual

HTML5 fantastic journey

It seems that the teacher once said that music is a universal language in the world. Yes. I don't understand English, but I can always enjoy English songs.

I wanted to be a music player a long time ago, but since the effect of displaying the current lyrics with a song has never been realized, my thoughts have never been realized. However, the idea has been poor recently and I am not in the mood to develop a game. So I am idle for some small inventions. This time, we will first imitate the display of the lyrics in Mobile QQ music.

Coincidentally, there were a lot of new songs at the end of the year, so I chose a nice song-a handwritten one.

First look at this demonstration:


Demo address: http://wyh.wjjsoft.com/demo/lyrics/

More than half of the above demo addresses may not be opened, because this one is nice, but there are 11 MB ....... If you want to listen, please go online and find it yourself.

Well, it's not a long journey. Go to the topic ~


I. interpreting the lyrics

Generally, the format of a lyrics file is a time pair of a lyrics, for example:

[Ti: handwriting from the past] [ar: Jay Chou] [t_time. 23] Jay Chou-handwriting from the past. 56] word: Fang Wenshan Qu: Jay Chou. 43] the wind chimes are very close to heart. This letter is still missing travel. 80] The love passing by is too young. You are the scenery I want to go back. 79] This separation is bottled as a secret this Daisy beautiful like a verse. 30] and I am waiting for your message in the wind to wait for the moonlight to fall into the snow. 92] I will relive the afternoon sun when I encounter maple blushing in autumn. 24] leaning your guitar on your shoulders as you did many years ago. 71] We gently sing anywhere. 54] I looked at your face and brushed the Chord. 00] Valentine's Day cards handwritten forever. 05] I still remember performing performances at the Square Park. 27] the memory of the candy shop next to the campus is slightly sweet. 99] I looked at your face and brushed the Chord. 31] The first love is the whole handwriting. 4.50] I still remember saying goodbye that fall. 51] when the relationship is gone, I will bury you in my heart. 25] The breeze needs to fly in bamboo streams. 59] a piece of duckweed is needed to leave the office in a bad mood. 17] Remember the rainy season memories of that year. 84] whether the decision after crying can be performed. 52] I am silly, waiting for silly, waiting for spring flowers to bloom. 80] The final equality is equal to the equality of the white and other love back. 40] youth belongs to the confession that sunshine belongs to the windowsill. 95] I think I belong to a future with you .............................. . 42] review the afternoon sun. 10] leaning your guitar on your shoulders as you did many years ago. 54] We gently sing anywhere. 53] I looked at your face and gently brushed the Chord. 98] Valentine's Day cards handwritten forever. 15] I still remember performing performances at the Square Park. 03] the memories of the candy store on campus are slightly sweet. 97] I looked at your face and brushed the chords. 26] The first love was written all over the past. 44] I still remember saying goodbye that fall. 50] When your relationship is far away, I will bury you in my heart
It is not difficult to find that square brackets represent not intervals but time except the first three rows. In the first three lines, the content in square brackets represents the song name, singer, and music length. But these are not the lyrics, so what we really want to deal with is the content after the first three lines. But it seems very troublesome to parse these things. What should I do? I want to use a regular expression, which is unfamiliar with regular expressions ...... So I had to think about some bad ideas.

In fact, we need to parse a format. To put it bluntly, we just need to find the rule. Looking for patterns. I heard that we have to look for patterns when testing IQ ......

As mentioned above, the format is roughly a time corresponding to a lyrics, Which is simplified to [time] lyrics [time2] lyrics2...

After mining the rules, I finally discovered the mysteries:

1) We first remove the \ n behind all the lyrics, so that the lyrics are arranged in a row;

2) each time + lyrics are separated;

3) The time and lyrics in each line are separated;

With these findings, the next step is to convert these strings into the data structure in the program. Here I have selected JSON as the structure for loading data. With this JSON, we can retrieve the lyrics by using the time directly in this JSON.


OK. I have roughly interpreted superficial things like lyrics. This is the code.


2. handwritten code

First, let's look at the most basic HTML code. For convenience, lufylegend. js is used in this development. If you want to know about this engine, you can refer to my previous articles. Most of them are about it.

<!DOCTYPE html>We also use the ytMain. js file. In this file, we first initialize the engine and a series of preparations:

LInit(50, "mylegend", 350, 550, main);var datalist = {};var music = null;function main () {document.body.style.background = "black";document.body.style.margin = "0px";document.body.style.padding = "0px";if (LGlobal.mobile) {LGlobal.stageScale = LStageScaleMode.SHOW_ALL;}LGlobal.screen(LGlobal.FULL_SCREEN);var loadData = [{path : "./js/ytLyrics.js"},{name : "pic", path : "./resource/albumpic.jpg"},{name : "lyrics", path : "./resource/shou_xie_de_cong_qian.js"},{name : "music", path : "./resource/shou_xie_de_cong_qian.mp3"}];var loadingLayer = new LoadingSample1();addChild(loadingLayer);LLoadManage.load(loadData,function (p) {loadingLayer.setProgress(p);},function (r) {datalist = r;loadingLayer.remove();addBackgroundPic();addTitle();addAlbumPic();addMusic();addLyrics();});}

The above code is to first use the internal function of the LInit engine to initialize the entire interface, and perform full screen processing, and then load images and music through the load function of the static LLoadManage class, add the loaded content to datalist, and then call the addBackgroundPic, addTitle, addAlbumPic, addMusic, and addLyrics functions to add display objects and play music. For the usage of LLoadManage and LInit engines, see the lufylegend. js API manual:

Http://lufylegend.com/api/zh_CN/out/index.html

To facilitate local testing, I directly wrote the lyrics to shou_xie_de_cong_qian.js. In this way, you can avoid the local running problems caused by Using ajax to read text files. Of course, in actual application, the lyrics are essentially a text file. They are read through ajax and then interpreted in a similar way as mentioned above. Next, let's take a look at shou_xie_de_cong_qian.js:

Var lyrics = "[ti: handwriting previous] [ar: Jay Chou] [t_time. 23] Jay Chou-handwriting from the past. 56] word: Fang Wenshan Qu: Jay Chou. 43] the wind chimes are very close to heart. This letter is still missing travel. 80] The love passing by is too young. You are the scenery I want to go back. 79] This separation is bottled as a secret this Daisy beautiful like a verse. 30] and I am waiting for your message in the wind to wait for the moonlight to fall into the snow. 92] I will relive the afternoon sun when I encounter maple blushing in autumn. 24] leaning your guitar on your shoulders as you did many years ago. 71] We gently sing anywhere. 54] I looked at your face and brushed the Chord. 00] Valentine's Day cards handwritten forever. 05] I still remember performing performances at the Square Park. 27] the memories of candy shops on campus are slightly sweet ............ ";
For the convenience of the figure, I manually changed all the lyrics into a line. Then you need to add the Display object:

Function addTitle () {var txt = new LTextField (); txt. text = "handwritten from the past"; txt. color = "white"; txt. size = 25; txt. x = (LGlobal. width-txt. getWidth ()/2; txt. y = 30; addChild (txt);} function addBackgroundPic () {var bmp = new LBitmapData (datalist ["pic"]); var bmp = new LBitmap (bmp D); bmp. scaleX = bmp. scaleY = 2; bmp. x = (LGlobal. width-bmp. getWidth ()/2; bmp. y = (LGlobal. height-bmp. getHeight ()/2; addChild (bmp); var curtain = new LSprite (); curtain. graphics. drawRect (0, "", [0, 0, LGlobal. width, LGlobal. height], true, "black"); curtain. alpha = 0.8; addChild (curtain);} function addAlbumPic () {var bmp = new LBitmapData (datalist ["pic"]); var bmp = new LBitmap (bmp D); bmp. scaleX = bmp. scale= 0.6; bmp. x = (LGlobal. width-bmp. getWidth ()/2; bmp. y = 100; addChild (bmp);} function addMusic () {music = new LSound (datalist ["music"]); music. play ();} function addLyrics () {var lyricsLayer = new ytLyrics (music, getLyrics (lyrics); lyricsLayer. x = (LGlobal. width-lyricsLayer. getWidth ()/2; lyricsLayer. y = 300; addChild (lyricsLayer );}
These functions mainly use several lufylegend classes: LTextField text class, LBitmap and LBitmapData bitmap class, LSound music class, And LSprite class. For more information about the usage, see the API reference manual. Here we will only talk about the addLyrics function. This function uses ytLyrics, a class I wrote myself. This class is derived from the LSprite class and is a display object. It is used to display the lyrics, as shown in the class name, there are two parameters: the first is the currently played music, and the second is the lyrics of the music. This class will be discussed later.

Next is the function for parsing the lyrics in ytMain. js:

function getLyrics (content) {var result = new Array();var cArr = content.split("[");cArr.shift();for (var i = 0; i < cArr.length; i++) {var o = cArr[i].split("]");if (o.length >= 2 && o[1] != "") {var tArr = o[0].split(":"), t = 0;if (tArr.length >= 2) {var mtArr = tArr[0].split(""), mt = 0;for (var k = 0; k < mtArr.length; k++) {if (Number(mtArr[k]) > 0) {mt += mtArr[k] * Math.pow(10, mtArr.length - k - 1);}}t += mt * 60;var stArr = tArr[1].split("."), intStArr = stArr[0].split(""), st = 0;for (var j = 0; j < intStArr.length; j++) {if (Number(intStArr[j]) > 0) {st += intStArr[j] * Math.pow(10, intStArr.length - j - 1);}}t += Number(st + "." + stArr[1]);}result.push({time : t, content : o[1]});}}return result;}

The code is not long, but the essence of this study is here. In shou_xie_de_cong_qian.js, we have defined a lyrics variable to load the lyrics. Therefore, the parameter passed to this function is lyrics. Here I mainly use the split of String to cut the String, loop through the cut array, and parse it until the time and lyrics are separated. Because the format of the lyrics is not too difficult, I just got the time and the corresponding lyrics in two minutes (for the first time, I scored, for the second time, press ). To remove the three items without lyrics, I used to determine whether the second element in the array obtained after the second cut was "" to block those items without lyrics. You can take a closer look at the code. It is not difficult to find that I put the result obtained after two cutting operations into JSON, then put JSON into the result array, and finally return the result array.

Maybe you will find that I used the t variable, which is the time at which the lyrics are finally uploaded to the result. Why do we need another t to display the time? The reason is very simple. When we get the current playback time in HTML5 Audio, we get the unit of seconds, but the time in our lyrics is in the form of [minute: Second], therefore, we must convert the format to a number in seconds. The implementation method is in the Code provided above. Split is mainly used to cut these time strings and obtain numbers in units and in seconds. Then t = the minute-to-minute number * 60 + second-to-second number will be able to get the final result.

After the lyrics are parsed, let's look at the ytLyrics class that displays the lyrics. This is the LSprite in lufylegend. After the LSprite, the parent's display attributes are added to the display, And the lyrics are displayed: this class is a subclass of LSprite in the lufylegend engine. It has the attributes and methods of the parent class LSprite in terms of display. In addition to the extended functions, the lyrics will be displayed ):

function ytLyrics (music, lyricsList) {var s = this;LExtends(s, LSprite, []);s.index = 0;s.list = lyricsList;s.music = music;s.scrollY = 0;s.contentLayer = new LSprite();s.addChild(s.contentLayer);s.showContent();s.addEventListener(LEvent.ENTER_FRAME, s.loop);}ytLyrics.prototype.showContent = function () {var s = this;for (var i = 0; i < s.list.length; i++) {var txt = new LTextField();txt.text = s.list[i].content;txt.color = "white";txt.x = (LGlobal.width - txt.getWidth()) / 2;txt.y = s.contentLayer.getHeight() + 20;s.contentLayer.addChild(txt)}s.scrollY = 30;var maskLayer = new LSprite();maskLayer.graphics.drawRect(0, "", [0, 0, LGlobal.width, 200]);s.contentLayer.mask = maskLayer;s.contentLayer.filters = [new LDropShadowFilter()]};ytLyrics.prototype.loop = function (e) {var s = e.currentTarget;if (s.index >= s.list.length) {return;}var ct = s.music.getCurrentTime();var minT = s.list[s.index].time,maxT = ((s.index + 1) < s.list.length) ? s.list[s.index + 1].time : s.music.length;if (ct >= minT && ct <= maxT) {var preTxt = s.contentLayer.getChildAt(s.index - 1);if (preTxt) {preTxt.color = "white";LTweenLite.to(s.contentLayer, 1, {y : s.contentLayer.y - preTxt.getHeight() - 20});}var currentTxt = s.contentLayer.getChildAt(s.index);if (currentTxt) {currentTxt.color = "#33FF00";}s.index ++;}};
The code is not long, And the ENTER_FRAME timeline event is mainly used to drive the rolling lyrics. Specifically, you can get the current time of the Song continuously in the timeline, and then get the time corresponding to the current lyrics and the time of the next lyrics in the lyrics list, compare the current time of the song with the time corresponding to the current lyrics and the time of the next lyrics to determine whether to play the next lyrics. The display still uses lufylegend, or that sentence. You just need to know the reference manual.


OK, run the code to get the desired effect.

3. Source Code download

We have discussed the essence of the above. You need to study other corners by yourself. If you have any other things that are not cleared, please leave a message below this article. I will try my best to reply to you ~

Source code: http://wyh.wjjsoft.com/downloads/lyrics.zip


This article is over. You are welcome to talk about it ~

----------------------------------------------------------------

You are welcome to repost my article.

Reprinted Please note:

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.