-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
56 lines (51 loc) · 2.15 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const { tmpdir } = require('os');
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
const fs = require('fs-extra');
const path = require('path');
const audioToSlice = async (buffer, seconds, video = false) => {
if (!buffer || !seconds)
throw new Error('Both media buffer and seconds are required.');
const extension = video ? 'mp4' : 'mp3'
const options = video ? '-reset_timestamps 1' : '-c:a libmp3lame'
const filename = path.join(tmpdir(), `${Math.random().toString(36)}.${extension}`);
await fs.writeFile(filename, buffer);
try {
const directory = 'temporary';
await fs.ensureDir(directory);
await exec(`ffmpeg -i ${filename} -f segment -segment_time ${seconds} ${options} ${directory}/document_%03d.${extension}`);
const files = await fs.readdir(directory);
const buffers = await Promise.all(files.map(x => fs.readFile(path.join(directory, x))));
await Promise.all([fs.unlink(filename), fs.remove(directory)]);
return buffers;
} catch (error) {
console.error(error.message);
return [];
}
}
const audioMerge = async (audios) => {
if (!Array.isArray(audios) || audios.length < 2) {
console.error('Input should be an array with at least two audio buffers.');
return audios?.[0] || [];
}
try {
const directory = 'temporary_merge';
await fs.ensureDir(directory);
audios.forEach(async (buffer, index) => {
const filename = path.join(directory, `audio_${index}.mp3`);
await fs.writeFile(filename, buffer);
});
const filename = path.join(tmpdir(), `${Math.random().toString(36)}.mp3`);
const files = audios.map((_, index) => `-i ${path.join(directory, `audio_${index}.mp3`)}`).join(' ');
await exec(
`ffmpeg ${files} -filter_complex concat=n=${audios.length}:v=0:a=1 -strict -2 ${filename}`
);
const buffer = await fs.readFile(filename);
await Promise.all([fs.unlink(filename), fs.remove(directory)]);
return buffer;
} catch (error) {
console.error(error.message);
return [];
}
}
module.exports = { audioMerge, audioToSlice }