網易雲歌詞解析(配合audio標籤實現本地歌曲播放,歌詞同步)

先看下效果html

github上作的一個音樂播放器: https://github.com/SorrowX/electron-musicgit

中文歌曲github

英文歌曲(若是有翻譯的中文給回返回出去)web

韓文歌曲spring

來看下解析歌詞的類json

class Lyric {
            constructor(data) {
                this.data = data
                this.lrc = data['lrc']['lyric']
                this.tlyric = data['tlyric']['lyric']

                this.lrcMap = this.getLyricMap(this.lrc)
                this.finalLrcMap = this.convertProp(Object.assign({}, this.lrcMap))

                this.tlyricMap = this.getLyricMap(this.tlyric)
                this.finalTlyricMap = this.convertProp(Object.assign({}, this.tlyricMap))
            }

            getLyricMap(lrc) {
                let key, value, sIdx, eIdx, nsIdx
                let ret = {}
                if (!lrc || (typeof lrc !== 'string')) return ret

                while(lrc) {
                    sIdx = lrc.indexOf('[')
                    eIdx = lrc.indexOf(']') + 1
                    if (sIdx !== -1 && eIdx !== -1) {
                        key = lrc.slice(sIdx, eIdx)
                        advance(eIdx)
                        nsIdx = lrc.indexOf('[')
                        value = lrc.slice(0, nsIdx)
                        ret[key] = value.trim()
                        advance(nsIdx)
                    } else {
                        break
                    }
                }

                function advance (n) {
                    lrc = lrc.substring(n)
                }
                return ret
            }

            convertProp(obj) {
                Object.keys(obj).forEach((str) => {
                    if (!obj[str]) {
                        delete obj[str]
                    } else {
                        let prop = f(str)
                        obj[prop] = obj[str]
                        delete obj[str]
                    }
                })

                function f(str) {
                    str = str.match(/^\[(\d+):(\d+)\.(\d+)/)
                    return Number(str[1]) * 60 * 1000 +  Number(str[2]) * 1000 +  Number(str[3])
                }
                return obj
            }

            getCurPlayLyric(audioCurTime) {
                let audioCurTimeMs = audioCurTime * 1000
                let arrTime = Object.keys(this.finalLrcMap)
                
                let i = 0, len = arrTime.length, idx
                let hasTranslate = Object.keys(this.finalTlyricMap).length > 0

                if (audioCurTimeMs === 0) {
                    return g.call(this, arrTime[0])
                }
                if (audioCurTimeMs >= Number(arrTime[len - 1])) {
                    return g.call(this, arrTime[len - 1])
                }
                for (; i < len; i++) {
                    if (
                        audioCurTimeMs >= Number(arrTime[i - 1]) && 
                        audioCurTimeMs < Number(arrTime[i])
                    ) {
                        idx = i - 1
                        break
                    }
                }
                return g.call(this, arrTime[idx])

                function g(prop) {
                    return hasTranslate 
                        ? v(this.finalLrcMap[prop]) + ('\n') + v(this.finalTlyricMap[prop])
                        : v(this.finalLrcMap[prop])
                }
                function v(val) {
                    return typeof val === 'undefined' ? '' : val
                }
            }
        }

使用姿式超級簡單
new Lyric(data)
data就是歌詞文件中的對象
使用實例 getCurPlayLyric 方法就ok,參數爲 audio.currentTime 單位秒 時間dom

看下完整demoelectron

let arrData = [
    {
        "sgc":false,
        "sfy":false,
        "qfy":false,
        "path": "D:\\SorrowX\\2018\\xhl-live-01\\trunk\\web-page\\歌詞\\十年.mp3",
        "name": "十年",
        "lrc":{
            "version":4,
            "lyric":`[00:00.00] 做曲 : 陳小霞
                [00:01.00] 做詞 : 林夕
                [00:03.700]編曲:唐漢霄
                [00:08.910]男:
                [00:09.650]
                [00:10.590]十年以後
                [00:12.510]
                [00:13.020]咱們是朋友還能夠問候
                [00:17.800]只是那種溫柔
                [00:20.840]再也找不到擁抱的理由
                [00:25.560]情人最後不免淪爲朋友
                [00:34.870]
                [00:48.850]女:
                [00:49.330]
                [00:50.730]若是那兩個字沒有顫抖
                [00:54.990]我不會發現我難受
                [00:58.660]怎麼說出口
                [01:00.630]
                [01:02.880]也不過是分手
                [01:04.920]
                [01:07.390]男:
                [01:08.040]若是對於明天沒有要求
                [01:11.710]
                [01:12.350]牽牽手就像旅遊
                [01:15.530]成千上萬個門口
                [01:17.990]
                [01:19.920]總有一我的要先走
                [01:22.880]
                [01:24.240]女:
                [01:24.720]
                [01:26.400]懷抱既然不能逗留
                [01:30.050]何不在離開的時候
                [01:33.280]一邊享受一邊淚流
                [01:40.470]
                [01:41.300]十年以前
                [01:43.530]我不認識你你不屬於我
                [01:47.670]咱們仍是同樣
                [01:50.400]陪在一個陌生人左右
                [01:54.660]走過漸漸熟悉的街頭
                [01:58.130]男:
                [01:58.480]十年以後
                [02:00.650]咱們是朋友還能夠問候
                [02:04.810]只是那種溫柔
                [02:07.500]再也找不到擁抱的理由
                [02:11.710]情人最後不免淪爲朋友
                [02:18.500]
                [02:37.240]懷抱既然不能逗留
                [02:40.870]何不在離開的時候
                [02:43.700]合:
                [02:43.900]一邊享受一邊淚流
                [02:51.140]
                [02:52.000]十年以前
                [02:54.170]我不認識你你不屬於我
                [02:58.430]咱們仍是同樣
                [03:01.100]陪在一個陌生人左右
                [03:04.520]男:
                [03:05.330]走過漸漸熟悉的街頭
                [03:09.070]十年以後
                [03:11.010]合:
                [03:11.430]咱們是朋友還能夠問候
                [03:15.580]只是那種溫柔
                [03:17.860]男:
                [03:18.320]再也找不到擁抱的理由
                [03:22.600]情人最後不免淪爲
                [03:26.670]合:
                [03:27.180]朋友
                [03:30.050]男:
                [03:30.550]
                [03:31.320]直到和你作了多年朋友
                [03:35.870]才明白個人眼淚
                [03:39.170]不是爲你而流
                [03:41.500]
                [03:43.500]也爲別人而流
            `
        },
        "tlyric":{
            "version":0,
            "lyric":null
        },
        "code":200
    },
    {
        "sgc":true,
        "sfy":true,
        "qfy":false,
        "path": "D:\\SorrowX\\2018\\xhl-live-01\\trunk\\web-page\\歌詞\\Buttons-The Pussycat Dolls-b.mp3",
        "name": "Buttons-The Pussycat Dolls-b",
        "transUser":{
            "id":19538200,
            "status":0,
            "demand":1,
            "userid":52624747,
            "nickname":"000落雪0",
            "uptime":1431834889776
        },
        "lrc":{
            "version":13,
            "lyric":`[00:00.00] 做曲 : Nicole Scherzinger & Sean Garrett & Jamal Jones & Jason Perry
            [00:19.530]I'm telling you loosen up my buttons baby (Uh huh)
            [00:22.840]But you keep fronting (Uh)
            [00:24.540]Saying what you going to do to me (Uh huh)
            [00:27.010]But I ain't seen nothing (Uh)
            [00:28.930]I'm telling you loosen up my buttons baby (Uh huh)
            [00:31.190]But you keep fronting (Uh)
            [00:33.500]Saying what you going to do to me (Uh huh)
            [00:35.780]But I ain't seen nothing (Uh)
            [00:39.740]Typical
            [00:40.400]Hardly the type I fall for
            [00:42.070]I'm liking the physical
            [00:44.120]Don't leave me asking for more
            [00:45.640]I'm a sexy mama (Mama)
            [00:48.070]Who knows just how to get what I want and (Want and)
            [00:50.730]What I want to do is spring this on you (On you)
            [00:52.990]Back up all of the things that I told you (Told you)
            [00:56.780]You been saying all the right things all along
            [01:00.450]But I can't seem to get you over here to help take this off
            [01:04.950]Baby, can't you see?
            [01:06.870]How these clothes are fitting on me
            [01:09.090]And the heat coming from this beat
            [01:11.370]I'm about to blow
            [01:13.230]I don't think you know
            [01:14.700]I'm telling you loosen up my buttons baby (Uh huh)
            [01:17.020]But you keep fronting (Uh)
            [01:19.240]Saying what you going to do to me (Uh huh)
            [01:22.020]But I ain't seen nothing (Uh)
            [01:24.180]I'm telling you loosen up my buttons baby (Uh huh)
            [01:26.400]But you keep fronting (Uh)
            [01:28.480]Saying what you going to do to me (Uh huh)
            [01:31.000]But I ain't seen nothing (Uh)
            [01:33.430]You say you're a big boy
            [01:35.560]But I can't agree
            [01:37.730]'Cause the love you said you had
            [01:40.090]Ain't been put on me
            [01:41.910]I wonder
            [01:43.250]If I'm just too much for you
            [01:44.650]Wonder
            [01:45.520]If my kiss don't make you just
            [01:46.480]Wonder
            [01:47.570]What I got next for you
            [01:48.840]What you want to do? (Do)
            [01:51.930]Take a chance to recognize that this could be yours
            [01:53.710]I can see, just like most guys that your game don't please
            [01:59.890]Baby, can't you see?
            [02:01.260]How these clothes are fitting on me
            [02:03.240]And the heat coming from this beat
            [02:05.750]I'm about to blow
            [02:07.360]I don't think you know
            [02:08.880]I'm telling you loosen up my buttons baby (Uh huh)
            [02:11.290]But you keep fronting (Uh)
            [02:13.590]Saying what you going to do to me (Uh huh)
            [02:15.560]But I ain't seen nothing (Uh)
            [02:18.100]I'm telling you loosen up my buttons baby (Uh huh)
            [02:20.370]But you keep fronting (Uh)
            [02:22.690]Saying what you going to do to me (Uh huh)
            [02:25.180]But I ain't seen nothing (Uh)
            [02:46.750]I'm a make you loosen up my buttons babe
            [02:47.960]Loosen up my buttons babe
            [02:49.980]Why don't you loosen up my buttons babe
            [02:52.000]Loosen up my buttons babe
            [02:54.310]I'm a make you loosen up my buttons babe
            [02:56.690]Loosen up my buttons babe
            [02:58.750]Why don't you loosen up my buttons babe
            [03:01.170]Loosen up my buttons babe
            [03:03.200]I'm telling you loosen up my buttons baby (Uh huh)
            [03:05.660]But you keep fronting (Uh)
            [03:07.980]Saying what you going to do to me (Uh huh)
            [03:10.070]But I ain't seen nothing (Uh)
            [03:12.230]I'm telling you loosen up my buttons baby (Uh huh)
            [03:14.460]But you keep fronting (Uh)
            [03:16.990]Saying what you going to do to me (Uh huh)
            [03:19.210]But I ain't seen nothing (Uh)
            [03:21.480]I'm telling you loosen up my buttons baby (Uh huh)
            [03:24.290]But you keep fronting (Uh)
            [03:26.240]Saying what you going to do to me (Uh huh)
            [03:28.390]But I ain't seen nothing (Uh)
            [03:30.500]I'm telling you loosen up my buttons baby (Uh huh)
            [03:32.750]But you keep fronting (Uh)
            [03:35.100]Saying what you going to do to me (Uh huh)
            [03:37.730]But I ain't seen nothing (Uh)
            `
        },
        "tlyric":{
            "version":1,
            "lyric":`[by:000落雪0]
            [00:19.530]我讓你鬆開個人鈕釦 寶貝
            [00:22.840]可是你站在我面前
            [00:24.540]問我 你將對我作些什麼
            [00:27.010]可是我什麼也沒說
            [00:28.930]我讓你你鬆開個人鈕釦 寶貝
            [00:31.190]可是你站在我面前
            [00:33.500]問我 你將對我作些什麼
            [00:35.780]可是我什麼也沒說
            [00:39.740]典型的
            [00:40.400]你幾乎就是我喜歡的類型
            [00:42.070]我喜歡你的身體
            [00:44.120]不要離開我,向我索取更多
            [00:45.640]我是火辣的女孩
            [00:48.070]人們都知道怎樣弄到我想要的
            [00:50.730]我想作的是向你涌出個人感情
            [00:52.990]實現全部我告訴你的事情
            [00:56.780]你曾說全部對的事情自始至終
            [01:00.450]可是我彷佛不能叫你過來幫我脫掉衣服
            [01:04.950]寶貝,你不知道嗎?
            [01:06.870]這些衣服是多麼的適合我
            [01:09.090]而且熱度來自於節拍
            [01:11.370]我快喘不過氣來了
            [01:13.230]我不認爲你知道
            [01:14.700]我讓你鬆開個人鈕釦 寶貝
            [01:17.020]可是你站在我面前
            [01:19.240]問我 你將對我作些什麼
            [01:22.020]可是我什麼也沒說
            [01:24.180]我讓你鬆開個人鈕釦 寶貝
            [01:26.400]可是你站在我面前
            [01:28.480]問我 你將對我作些什麼
            [01:31.000]可是我什麼也沒說
            [01:33.430]你說你是個大男孩
            [01:35.560]可是我不一樣意
            [01:37.730]由於你說過你愛我
            [01:40.090]別在我面前裝
            [01:41.910]我想
            [01:43.250]若是我對你來講很合適
            [01:44.650]我想
            [01:45.520]若是我吻你能讓你也
            [01:46.480]我想
            [01:47.570]下一步我該怎麼作
            [01:48.840]你想讓我怎麼作?
            [01:51.930]給你一個機會辨認出這些是你的
            [01:53.710]我敢說,就跟大多數人認爲的那樣你的遊戲根本不討人喜歡
            [01:59.890]寶貝,你不知道嗎?
            [02:01.260]這些衣服是多麼的適合我
            [02:03.240]而且熱度來自於節拍
            [02:05.750]我快喘不過氣來了
            [02:07.360]我不認爲你知道
            [02:08.880]我讓你鬆開個人鈕釦 寶貝
            [02:11.290]可是你站在我面前
            [02:13.590]問我 你將對我作些什麼
            [02:15.560]可是我什麼也沒說
            [02:18.100]我讓你鬆開個人鈕釦 寶貝
            [02:20.370]可是你站在我面前
            [02:22.690]問我 你將對我作些什麼
            [02:25.180]可是我什麼也沒說
            [02:46.750]我一再讓你解開個人鈕釦 寶貝
            [02:47.960]解開個人鈕釦 寶貝
            [02:49.980]你爲何不願解開個人鈕釦 寶貝
            [02:52.000]解開個人鈕釦 寶貝
            [02:54.310]我一再讓你解開個人鈕釦 寶貝
            [02:56.690]解開個人鈕釦 寶貝
            [02:58.750]你爲何不願解開個人鈕釦 寶貝
            [03:01.170]解開個人鈕釦 寶貝
            [03:03.200]我讓你鬆開個人鈕釦 寶貝
            [03:05.660]可是你站在我面前
            [03:07.980]問我 你將對我作些什麼
            [03:10.070]可是我什麼也沒說
            [03:12.230]我讓你鬆開個人鈕釦 寶貝
            [03:14.460]可是你站在我面前
            [03:16.990]問我 你將對我作些什麼
            [03:19.210]可是我什麼也沒說
            [03:21.480]我讓你鬆開個人鈕釦 寶貝
            [03:24.290]可是你站在我面前
            [03:26.240]問我 你將對我作些什麼
            [03:28.390]可是我什麼也沒說
            [03:30.500]我讓你鬆開個人鈕釦 寶貝
            [03:32.750]可是你站在我面前
            [03:35.100]問我 你將對我作些什麼
            [03:37.730]可是我什麼也沒說
            `
        },
        "code":200
    },
    {
        "sgc":true,
        "sfy":false,
        "qfy":false,
        "path": "D:\\SorrowX\\2018\\xhl-live-01\\trunk\\web-page\\歌詞\\和寂寞說分手-愛戴-b.mp3",
        "name": "和寂寞說分手",
        "lrc":{
            "version":4,
            "lyric":`[00:00.00] 做曲 : 和寂寞說分手(粵語版)
            [00:02.25]和寂寞說分手
            [00:05.86]和快樂 Say Don't Go
            [00:20.13][00:08.96]
            [00:20.56]停留在十字路口
            [00:26.01]心情在四處飄遊
            [00:29.90]告別曾經的溫柔
            [00:32.11]讓一切再從頭
            [00:37.31]收拾曾經的心情
            [00:39.74]讓心不在四處飄遊
            [00:42.95]忘記曾經的逗留
            [00:47.19]改變一些節奏
            [00:54.70]和寂寞說分手
            [00:58.41]和快樂 Say Don't Go
            [01:01.89]
            [01:02.12]若是說曾經是擁有
            [01:05.82]又何苦會淚流
            [01:09.56]和寂寞說分手
            [01:12.97]拋棄全部的全部
            [01:17.07]原來曾擁有的一切
            [01:20.82]全均可以放棄
            [01:23.80]個人自由
            [01:34.00]
            [01:34.18]不要說難以忘記
            [01:35.90]那是懦弱的理由
            [01:39.20]語不驚人死不休
            [01:43.28]這次是本身
            [01:46.21]徹底放本身自由
            [01:52.93]
            [01:53.12]和寂寞說分手
            [01:56.40]和快樂 Say Don't Go
            [02:00.17]若是說曾經是擁有
            [02:03.80]又何苦會淚流
            [02:07.67]和寂寞說分手
            [02:11.11]拋棄全部的全部
            [02:15.20]原來曾擁有的一切
            [02:18.99]全均可以放棄
            [02:21.95]個人自由
            [02:27.24]
            [02:30.27]若是新的開始
            [02:32.12]還是又想回頭
            [02:35.68]那就承受更多的難受
            [02:44.55]
            [02:45.30]和寂寞說分手
            [02:48.84]和快樂 Say Don't Go
            [02:52.81]若是說曾經是擁有
            [02:56.43]又何苦會淚流
            [03:00.22]和寂寞說分手
            [03:03.65]拋棄全部的全部
            [03:07.60]原來曾擁有的一切
            [03:11.41]全均可以放棄
            [03:14.30]個人自由
            [03:19.05]全均可以放棄
            [03:24.45]個人自由
            `
        },
        "tlyric":{
            "version":0,
            "lyric":null
        },
        "code":200
    },
    {
        "sgc":false,
        "sfy":false,
        "qfy":false,
        "path": "D:\\SorrowX\\2018\\xhl-live-01\\trunk\\web-page\\歌詞\\江南Style-信-b.mp3",
        "name": "江南Style-信",
        "lrc":{
            "version":7,
            "lyric":`[00:00.00] 做曲 : PSY/유건형(Yoo Gun hyung)
            [00:00.341] 做詞 : PSY
            [00:01.23]編曲 : 劉穎嶸
            [00:20.58]오빤 강남스타일
            [00:24.59]강남스타일
            [00:29.82]낮에는 따사로운 인간적인 여자
            [00:33.08]커피 한잔의 여유를 아는 품격 있는 여자
            [00:36.71]밤이 오면 심장이 뜨거워지는 여자
            [00:40.25]그런 반전 있는 여자
            [00:43.98]나는 사나이
            [00:45.61]낮에는 너만큼 따사로운 그런 사나이
            [00:49.15]커피 식기도 전에 원샷 때리는 사나이
            [00:52.94]밤이 오면 심장이 터져버리는 사나이
            [00:56.45]그런 사나이
            [00:58.80]아름다워 사랑스러워
            [01:02.25]그래 너 hey 그래 바로 너 hey
            [01:06.19]아름다워 사랑스러워
            [01:09.71]그래 너 hey 그래 바로 너 hey
            [01:13.63]지금부터 갈 데까지 가볼까
            [01:21.92]오빤 강남스타일 강남스타일
            [01:27.01]오오오오 오빤 강남스타일
            [01:33.14]강남스타일
            [01:34.43]오오오오 오빤 강남스타일
            [01:38.02]Eh- Sexy Lady
            [01:41.65]오오오오 오빤 강남스타일
            [01:45.23]Eh- Sexy Lady
            [01:48.98]오오오오
            [02:00.18]정숙해 보이지만 놀 땐 노는 여자
            [02:03.57]이때다 싶으면 묶었던 머리 푸는 여자
            [02:07.12]가렸지만 웬만한 노출보다 야한 여자
            [02:10.63]그런 감각적인 여자
            [02:14.38]나는 사나이
            [02:16.13]점잖아 보이지만 놀 땐 노는 사나이
            [02:19.64]때가 되면 완전 미쳐버리는 사나이
            [02:23.28]근육보다 사상이 울퉁불퉁한 사나이
            [02:26.94]그런 사나이
            [02:29.31]아름다워 사랑스러워
            [02:32.65]그래 너 hey 그래 바로 너 hey
            [02:36.49]아름다워 사랑스러워
            [02:40.04]그래 너 hey 그래 바로 너 hey
            [02:43.73]지금부터 갈 데까지 가볼까
            [02:51.90]오빤 강남 스타일 강남스타일
            [02:57.45]오오오오 오빤 강남스타일
            [03:03.83]강남스타일
            [03:04.69]오오오오 오빤 강남스타일
            [03:08.44]Eh- Sexy Lady
            [03:12.11]오오오오 오빤 강남스타일
            [03:15.87]Eh- Sexy Lady
            [03:19.40]오오오오
            [03:23.22]뛰는 놈 그 위에 나는 놈
            [03:26.06]baby baby
            [03:27.44]나는 뭘 좀 아는 놈
            [03:30.21]뛰는 놈 그 위에 나는 놈
            [03:33.36]baby baby
            [03:34.23]나는 뭘 좀 아는 놈
            [03:36.57]You know what I'm saying
            [03:56.46][03:41.77]Eh- Sexy Lady
            [04:00.16][03:45.29]오오오오 오빤 강남스타일
            [04:03.75][03:48.87]Eh- Sexy Lady
            [04:07.43][03:52.73]오오오오 오빤 강남스타일
            `
        },
        "tlyric":{
            "version":3,
            "lyric":`[00:20.58]哥哥是 江南style
            [00:24.59]江南style
            [00:29.82]白天是充滿溫暖人情味的女人
            [00:33.08]有品位 也懂得享受咖啡的女人
            [00:36.71]若是到了晚上 心臟是火熱熱的女人
            [00:40.25]有那種反差性格的女人
            [00:43.98]我是男子漢
            [00:45.61]白天是像你那樣溫暖的男子漢
            [00:49.15]就算喝咖啡也是乾杯的男子漢
            [00:52.94]若是到了晚上 心跳開始加快的男子漢
            [00:56.45]是那樣的男子漢
            [00:58.80]美麗的 可愛的
            [01:02.25]沒錯 是你 Hey 沒錯就是你 Hey
            [01:06.19]美麗的 可愛的
            [01:09.71]沒錯 是你 Hey 沒錯就是你 Hey
            [01:13.63]如今開始到衝破極限以前 一塊兒走吧
            [01:21.92]哥哥是 江南style 江南style
            [01:27.01]哥哥是 江南style
            [01:33.14]江南style
            [01:34.43]哥哥是 江南style
            [01:41.65]哥哥是 江南style
            [01:48.98]Oh Oh Oh Oh
            [02:00.18]雖然看似文靜卻很懂得玩樂的女人
            [02:03.57]時機到了 髮束也會放開的女人
            [02:07.12]雖然遮掩 但比起裸露還要更性感的女人
            [02:10.63]有那種性感魅力的女人
            [02:14.38]我是男子漢
            [02:16.13]雖然看似穩重卻很懂得玩樂的男子漢
            [02:19.64]時機到了 會徹底失控的男子漢
            [02:23.28]思想比肌肉更加發達的男子漢
            [02:26.94]是那樣的男子漢
            [02:29.31]美麗的 可愛的
            [02:32.65]沒錯 是你 Hey 沒錯就是你 Hey
            [02:36.49]美麗的 可愛的
            [02:40.04]沒錯 是你 Hey 沒錯就是你 Hey
            [02:43.73]如今開始到衝破極限以前 一塊兒走吧
            [02:51.90]哥哥是 江南style
            [02:57.45]哥哥是 江南style
            [03:03.83]江南style
            [03:04.69]哥哥是 江南style
            [03:12.11]哥哥是 江南style
            [03:19.40]Oh Oh Oh Oh
            [03:23.22]一山還有一山高
            [03:27.44]我是知道些什麼的人
            [03:30.21]一山還有一山高
            [03:34.23]我是知道些什麼的人
            [04:00.16][03:45.29]哥哥是 江南style
            [04:07.43][03:52.73]哥哥是 江南style`
        },
        "code":200
    }
]


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>song</title>
    <style>
        .box {
            width: 400px;
            margin: 240px auto;
        }
        .btn {
            display: inline-block;
            width: 80px;
            height: 24px;
            border: 1px solid #eee;
            margin-bottom: 20px;
        }
        .audio {
            display: block;
        }
        .span {
            margin-left: 20px;
        }
        .pre {
            font-family: sans-serif;
        }
    </style>
</head>
<body>
    <div class="box">
        <button id="btn" class="btn">切歌</button>
        <span id="span" class="span"></span>
        <audio id="audio" class="audio" controls="controls"></audio>
        <pre id="lyric" class="pre"></pre>
    </div>
    
    <script src="./json.js"></script>
    <script>
        let ly = null

        let cutSong = function() {
            let data = arrData[Math.floor(Math.random() * arrData.length)]
            audio.src = data.path
            span.innerHTML = `歌曲: ${data.name}`
            ly = new Lyric(data)
            audio.play()
        }

        class Lyric {
            constructor(data) {
                this.data = data
                this.lrc = data['lrc']['lyric']
                this.tlyric = data['tlyric']['lyric']

                this.lrcMap = this.getLyricMap(this.lrc)
                this.finalLrcMap = this.convertProp(Object.assign({}, this.lrcMap))

                this.tlyricMap = this.getLyricMap(this.tlyric)
                this.finalTlyricMap = this.convertProp(Object.assign({}, this.tlyricMap))
            }

            getLyricMap(lrc) {
                let key, value, sIdx, eIdx, nsIdx
                let ret = {}
                if (!lrc || (typeof lrc !== 'string')) return ret

                while(lrc) {
                    sIdx = lrc.indexOf('[')
                    eIdx = lrc.indexOf(']') + 1
                    if (sIdx !== -1 && eIdx !== -1) {
                        key = lrc.slice(sIdx, eIdx)
                        advance(eIdx)
                        nsIdx = lrc.indexOf('[')
                        value = lrc.slice(0, nsIdx)
                        ret[key] = value.trim()
                        advance(nsIdx)
                    } else {
                        break
                    }
                }

                function advance (n) {
                    lrc = lrc.substring(n)
                }
                return ret
            }

            convertProp(obj) {
                Object.keys(obj).forEach((str) => {
                    if (!obj[str]) {
                        delete obj[str]
                    } else {
                        let prop = f(str)
                        obj[prop] = obj[str]
                        delete obj[str]
                    }
                })

                function f(str) {
                    str = str.match(/^\[(\d+):(\d+)\.(\d+)/)
                    return Number(str[1]) * 60 * 1000 +  Number(str[2]) * 1000 +  Number(str[3])
                }
                return obj
            }

            getCurPlayLyric(audioCurTime) {
                let audioCurTimeMs = audioCurTime * 1000
                let arrTime = Object.keys(this.finalLrcMap)
                
                let i = 0, len = arrTime.length, idx
                let hasTranslate = Object.keys(this.finalTlyricMap).length > 0

                if (audioCurTimeMs === 0) {
                    return g.call(this, arrTime[0])
                }
                if (audioCurTimeMs >= Number(arrTime[len - 1])) {
                    return g.call(this, arrTime[len - 1])
                }
                for (; i < len; i++) {
                    if (
                        audioCurTimeMs >= Number(arrTime[i - 1]) && 
                        audioCurTimeMs < Number(arrTime[i])
                    ) {
                        idx = i - 1
                        break
                    }
                }
                return g.call(this, arrTime[idx])

                function g(prop) {
                    return hasTranslate 
                        ? v(this.finalLrcMap[prop]) + ('\n') + v(this.finalTlyricMap[prop])
                        : v(this.finalLrcMap[prop])
                }
                function v(val) {
                    return typeof val === 'undefined' ? '' : val
                }
            }
        }

        audio.addEventListener('timeupdate', () => {
            lyric.innerHTML = ly.getCurPlayLyric(audio.currentTime) 
        }, false)

        btn.addEventListener('click', () => {
            cutSong()
        }, false)

    </script>
</body>
</html>
相關文章
相關標籤/搜索