From ce8760a39ab74d826889b63d205d00ca39507045 Mon Sep 17 00:00:00 2001 From: Nepenthe <113700307+pohgxz@users.noreply.github.com> Date: Wed, 30 Oct 2024 21:09:32 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=20(#478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/onebot/action/file/GetRecord.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/onebot/action/file/GetRecord.ts b/src/onebot/action/file/GetRecord.ts index 742a8b50..c62e1574 100644 --- a/src/onebot/action/file/GetRecord.ts +++ b/src/onebot/action/file/GetRecord.ts @@ -5,9 +5,11 @@ import { promises as fs } from 'fs'; import { decode } from 'silk-wasm'; const FFMPEG_PATH = process.env.FFMPEG_PATH || 'ffmpeg'; -interface Payload extends GetFilePayload { - out_format: 'mp3' | 'amr' | 'wma' | 'm4a' | 'spx' | 'ogg' | 'wav' | 'flac'; -} +const out_format = ['mp3' , 'amr' , 'wma' , 'm4a' , 'spx' , 'ogg' , 'wav' , 'flac']; + +type Payload = { + out_format : string +} & GetFilePayload export default class GetRecord extends GetFileBase { actionName = ActionName.GetRecord; @@ -17,12 +19,19 @@ export default class GetRecord extends GetFileBase { if (payload.out_format && typeof payload.out_format === 'string') { const inputFile = res.file; if (!inputFile) throw new Error('file not found'); + if (!out_format.includes(payload.out_format)) { + throw new Error('转换失败 out_format 字段可能格式不正确'); + } const pcmFile = `${inputFile}.pcm`; const outputFile = `${inputFile}.${payload.out_format}`; try { await fs.access(inputFile); - await this.decodeFile(inputFile, pcmFile); - await this.convertFile(pcmFile, outputFile, payload.out_format); + try { + await fs.access(outputFile); + } catch (error) { + await this.decodeFile(inputFile, pcmFile); + await this.convertFile(pcmFile, outputFile, payload.out_format); + } const base64Data = await fs.readFile(outputFile, { encoding: 'base64' }); res.file = outputFile; res.url = outputFile; @@ -48,7 +57,8 @@ export default class GetRecord extends GetFileBase { private convertFile(inputFile: string, outputFile: string, format: string): Promise { return new Promise((resolve, reject) => { - const ffmpeg = spawn(FFMPEG_PATH, ['-f', 's16le', '-ar', '24000', '-ac', '1', '-i', inputFile, outputFile]); + const params = format === 'amr' ? ['-f', 's16le', '-ar', '24000', '-ac', '1', '-i', inputFile, '-ar', '8000', '-b:a', '12.2k', outputFile] : ['-f', 's16le', '-ar', '24000', '-ac', '1', '-i', inputFile, outputFile]; + const ffmpeg = spawn(FFMPEG_PATH, params); ffmpeg.on('close', (code) => { if (code === 0) { @@ -63,4 +73,4 @@ export default class GetRecord extends GetFileBase { }); }); } -} \ No newline at end of file +}