Follow us 登录 注册

将JSON 格式的歌词数据转换为标准 LRC 格式

function convertToLrc(lyricsData) {

    // 检查数据是否存在

    if (!lyricsData || !lyricsData.sentences || !Array.isArray(lyricsData.sentences)) {

        return "";

    }


    // 遍历每一行歌词进行转换

    const lrcLines = lyricsData.sentences.map(sentence => {

        const timeMs = sentence.startMs; // 获取开始时间(毫秒)

        const text = sentence.text || ""; // 获取歌词文本


        // 1. 计算分、秒、毫秒

        // 总秒数

        const totalSeconds = timeMs / 1000;

        // 分

        const minutes = Math.floor(totalSeconds / 60);

        // 剩余秒

        const seconds = Math.floor(totalSeconds % 60);

        // 毫秒(LRC通常取两位,即10毫秒单位)

        const milliseconds = Math.floor((timeMs % 1000) / 10);


        // 2. 格式化补零 (例如 9 -> 09, 5 -> 05)

        const mm = String(minutes).padStart(2, '0');

        const ss = String(seconds).padStart(2, '0');

        const ms = String(milliseconds).padStart(2, '0');


        // 3. 拼接 LRC 标签格式 [mm:ss.xx]

        return `[${mm}:${ss}.${ms}]${text}`;

    });


    // 将数组用换行符连接成字符串

    return lrcLines.join('\n');

}


// --- 测试使用 ---


// 这是你提供的数据片段

const rawData = {

    "lyricType": "krc",

    "sentences": [

        {

            "startMs": 0,

            "endMs": 9035,

            "text": "作曲:怪阿姨",

            "words": [{ "text": "作曲:怪阿姨", "startMs": 0, "endMs": 9035 }],

            "type": "lrc"

        },

        {

            "startMs": 9035,

            "endMs": 18070,

            "text": "作词:怪阿姨",

            "words": [{ "text": "作词:怪阿姨", "startMs": 9035, "endMs": 18070 }],

            "type": "lrc"

        },

        {

            "text": "看着我的眼睛",

            "startMs": 18070,

            "endMs": 19600,

            "words": [

                { "startMs": 18070, "endMs": 18380, "text": "看" }

                // ...省略其他字

            ],

            "type": "lrc"

        }

    ]

};


// 执行转换

const lrcResult = convertToLrc(rawData);

console.log(lrcResult);