这次也是上次的延续(QRC与LRC合并),不过这次是多个LRC文件合并。这次是纯C++,不过代码风格不太好,毕竟也就只是一个小时坑出来的,没有写什么注释。
参数就是LRC文件的路径,非时间标签为处理。默认误差范围是600ms,以第一个LRC文件为准。
// // main.cpp // LRCCombiner // // Created by Ryza 15/4/27. // Copyright (c) 2015年 Ryza. All rights reserved. // #include <iostream> #include <string> #include <iostream> #include <fstream> #include <regex.h> #include <map> #include <vector> using namespace std; map<long long, vector<string>> lyrics; int main(int argc, const char * argv[]) { if (argc < 3) return 0; for (int index = 1; index < argc; index++) { ifstream LRC_in(argv[index]); if (!LRC_in) { printf("[ERROR] Can't open file at %s\n",argv[index]); continue; } string str; int cflags = REG_EXTENDED; regex_t reg; const char * pattern = "^\\[([0-9]+).([0-9]+).([0-9]+)"; // 匹配以'['开头, 并且后面跟着数字的就行了 regcomp(®, pattern, cflags); regmatch_t pm[10]; const size_t nmatch = 10; int result; while(getline(LRC_in, str)) { result = regexec(®, str.c_str(), nmatch, pm, 0); if (result == REG_NOMATCH) continue; else if (result != 0) { char ebuf[128]; regerror(result, ®, ebuf, sizeof(ebuf)); printf("[ERROR] Error on regexec: %s\n",ebuf); regfree(®); continue; } else { const char * line = str.c_str(); long long microseconds = 0; int pos = 0; for (int x = 1; x < nmatch && pm[x].rm_so != -1; x++) { char * mstr = strndup(line + pm[x].rm_so, pm[x].rm_eo-pm[x].rm_so); if (pos % 3 == 0) microseconds += atoll(mstr) * 60 * 1000; else if (pos % 3 == 1) microseconds += atoll(mstr) * 1000; else { microseconds += atoll(mstr) * 10; char * lrc = (char *)malloc(sizeof(char) * 512); for(int i = 10; i < strlen(line); i++) lrc[i - 10] = line[i]; if (index != 1) { for (map<long long, vector<string>>::iterator lyric = lyrics.begin(); lyric != lyrics.end(); lyric++) { long long microsecondInRecord = lyric->first; if (microseconds >= microsecondInRecord - 300 && microseconds <= microsecondInRecord + 300) { lyrics[microsecondInRecord].push_back(string(lrc)); break; } } } else lyrics[microseconds].push_back(string(lrc)); memset(lrc, 0, sizeof(char) * 512); free(lrc); } free(mstr); pos++; } } } } for (map<long long, vector<string>>::iterator lyric = lyrics.begin(); lyric != lyrics.end(); lyric++) { long long microseconds = lyric->first; double seconds = microseconds / 1000.0; int min = seconds / 60; double sec = seconds - 60 * min; printf("[%02d:%05.2lf] ",min,sec); vector<string> t = lyrics[microseconds]; t.reserve(argc - 1); while (! t.empty()) { printf("%s ",t.back().c_str()); t.pop_back(); } printf("\n"); } return 0; }
GitHub: #/LRCCombiner