Skip to content

Commit

Permalink
🗿
Browse files Browse the repository at this point in the history
  • Loading branch information
ImYanXiao authored Oct 8, 2024
1 parent c9a58bd commit b0c118b
Showing 1 changed file with 38 additions and 29 deletions.
67 changes: 38 additions & 29 deletions lib/converter.js
Original file line number Diff line number Diff line change
@@ -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);
}
})
});
}

/**
Expand All @@ -48,7 +57,7 @@ function toPTT(buffer, ext) {
'-c:a', 'libopus',
'-b:a', '128k',
'-vbr', 'on',
], ext, 'ogg')
], ext, 'ogg');
}

/**
Expand All @@ -64,7 +73,7 @@ function toAudio(buffer, ext) {
'-b:a', '128k',
'-vbr', 'on',
'-compression_level', '10'
], ext, 'opus')
], ext, 'opus');
}

/**
Expand All @@ -81,12 +90,12 @@ function toVideo(buffer, ext) {
'-ar', '44100',
'-crf', '32',
'-preset', 'slow'
], ext, 'mp4')
], ext, 'mp4');
}

export {
toAudio,
toPTT,
toVideo,
ffmpeg
}
};

0 comments on commit b0c118b

Please sign in to comment.