Files
SPlayer/electron/main/utils/helper.ts

59 lines
1.6 KiB
TypeScript
Raw Normal View History

import { createHash } from "crypto";
import { readFile } from "fs/promises";
/**
* ID
* @param filePath
* @returns ID
*/
export const getFileID = (filePath: string): number => {
// SHA-256
const hash = createHash("sha256");
hash.update(filePath);
const digest = hash.digest("hex");
// 将哈希值的前 16 位转换为十进制数字
const uniqueId = parseInt(digest.substring(0, 16), 16);
return Number(uniqueId.toString().padStart(16, "0"));
};
/**
* MD5
* @param path
* @returns MD5值
*/
export const getFileMD5 = async (path: string): Promise<string> => {
const data = await readFile(path);
const hash = createHash("md5");
hash.update(data);
return hash.digest("hex");
};
/**
* music-metadata LRC格式字符串
* @param lyrics
* @returns LRC格式的字符串
*/
export const metaDataLyricsArrayToLrc = (
lyrics: {
text: string;
timestamp?: number;
}[],
): string => {
return lyrics
.map(({ timestamp, text }) => {
if (!timestamp) return "";
const totalSeconds = Math.floor(timestamp / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const centiseconds = Math.floor((timestamp % 1000) / 10);
// 格式化为两位数字
const mm = String(minutes).padStart(2, "0");
const ss = String(seconds).padStart(2, "0");
const cs = String(centiseconds).padStart(2, "0");
return `[${mm}:${ss}.${cs}]${text}`;
})
.join("\n");
};