This commit is contained in:
idanran 2024-04-04 04:22:56 +00:00
parent 1f8966aaf4
commit ab91313e69

View File

@ -6,7 +6,7 @@ import path from "node:path";
import {DATA_DIR, TEMP_DIR} from "./index"; import {DATA_DIR, TEMP_DIR} from "./index";
import {v4 as uuidv4} from "uuid"; import {v4 as uuidv4} from "uuid";
import {getConfigUtil} from "../config"; import {getConfigUtil} from "../config";
import ffmpeg from "fluent-ffmpeg"; import {spawn} from "node:child_process"
export async function encodeSilk(filePath: string) { export async function encodeSilk(filePath: string) {
function getFileHeader(filePath: string) { function getFileHeader(filePath: string) {
@ -66,30 +66,26 @@ export async function encodeSilk(filePath: string) {
const _isWav = await isWavFile(filePath); const _isWav = await isWavFile(filePath);
const pcmPath = pttPath + ".pcm" const pcmPath = pttPath + ".pcm"
let sampleRate = 0 let sampleRate = 0
const convert = async () => { const convert = () => {
return await new Promise<Buffer>((resolve, reject) => { return new Promise<Buffer>((resolve, reject) => {
const ffmpegPath = getConfigUtil().getConfig().ffmpeg; const ffmpegPath = getConfigUtil().getConfig().ffmpeg || process.env.FFMPEG_PATH || "ffmpeg"
if (ffmpegPath) { const cp = spawn(ffmpegPath, ["-y", "-i", filePath, "-ar", "24000", "-ac", "1", "-f", "s16le", pcmPath])
ffmpeg.setFfmpegPath(ffmpegPath); cp.on("error", err => {
} log(`FFmpeg处理转换出错: `, err.message)
ffmpeg(filePath) return reject(err)
.outputOptions([ })
"-ar 24000", cp.on("exit", (code, signal) => {
"-ac 1", const EXIT_CODES = [0, 255]
"-f s16le" if (code == null || EXIT_CODES.includes(code)) {
])
.on("error", function (err) {
log(`ffmpeg转换出错: `, err.message);
reject(err);
})
.on("end", () => {
sampleRate = 24000 sampleRate = 24000
const data = fs.readFileSync(pcmPath) const data = fs.readFileSync(pcmPath)
fs.unlink(pcmPath, (err) => { fs.unlink(pcmPath, (err) => {
}) })
resolve(data) return resolve(data)
}) }
.save(pcmPath); log(`FFmpeg exit: code=${code ?? "unknown"} sig=${signal ?? "unknown"}`)
reject(Error(`FFmpeg处理转换失败`))
})
}) })
} }
let input: Buffer let input: Buffer