网易云歌词解析(配合audio标签实现本地歌曲播放,歌词同步)

倖福魔咒の 提交于 2020-05-04 10:18:24

先看下效果

github上做的一个音乐播放器: https://github.com/SorrowX/electron-music

中文歌曲

英文歌曲(如果有翻译的中文给回返回出去)

韩文歌曲

来看下解析歌词的类

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 单位秒 时间

看下完整demo

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>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!