From b0c118b43a4c8c4455a1234142945ee8f210293c Mon Sep 17 00:00:00 2001 From: Xiao Yan? <102222065+ImYanXiao@users.noreply.github.com> Date: Wed, 9 Oct 2024 00:29:47 +0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/converter.js | 67 +++++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/lib/converter.js b/lib/converter.js index 228cf86e9..f75bba7ad 100644 --- a/lib/converter.js +++ b/lib/converter.js @@ -1,39 +1,48 @@ -import { promises } from 'fs' -import { join } from 'path' -import { spawn } from 'child_process' +import { promises } from 'fs'; +import { join } from 'path'; +import { spawn } from 'child_process'; +import { fileURLToPath } from 'url'; + +const __dirname = fileURLToPath(new URL('.', import.meta.url)); function ffmpeg(buffer, args = [], ext = '', ext2 = '') { return new Promise(async (resolve, reject) => { try { - let tmp = join(global.__dirname(import.meta.url), '../tmp', + new Date + '.' + ext) - let out = tmp + '.' + ext2 - await promises.writeFile(tmp, buffer) - spawn('ffmpeg', [ + let tmp = join(__dirname, '../tmp', +new Date() + '.' + ext); + let out = tmp + '.' + ext2; + await promises.writeFile(tmp, buffer); + const ffmpegProcess = spawn('ffmpeg', [ '-y', '-i', tmp, ...args, out - ]) - .on('error', reject) - .on('close', async (code) => { - try { - await promises.unlink(tmp) - if (code !== 0) return reject(code) - resolve({ - data: await promises.readFile(out), - filename: out, - delete() { - return promises.unlink(out) - } - }) - } catch (e) { - reject(e) + ]); + ffmpegProcess.on('error', (err) => { + console.error('Error spawning ffmpeg:', err); + reject(err); + }); + ffmpegProcess.on('close', async (code) => { + try { + await promises.unlink(tmp); + if (code !== 0) return reject(code); + if (!await promises.access(out).then(() => true).catch(() => false)) { + return reject(new Error('Output file not found')); } - }) + resolve({ + data: await promises.readFile(out), + filename: out, + delete() { + return promises.unlink(out); + } + }); + } catch (e) { + reject(e); + } + }); } catch (e) { - reject(e) + reject(e); } - }) + }); } /** @@ -48,7 +57,7 @@ function toPTT(buffer, ext) { '-c:a', 'libopus', '-b:a', '128k', '-vbr', 'on', - ], ext, 'ogg') + ], ext, 'ogg'); } /** @@ -64,7 +73,7 @@ function toAudio(buffer, ext) { '-b:a', '128k', '-vbr', 'on', '-compression_level', '10' - ], ext, 'opus') + ], ext, 'opus'); } /** @@ -81,7 +90,7 @@ function toVideo(buffer, ext) { '-ar', '44100', '-crf', '32', '-preset', 'slow' - ], ext, 'mp4') + ], ext, 'mp4'); } export { @@ -89,4 +98,4 @@ export { toPTT, toVideo, ffmpeg -} +};