Skip to content

Commit 401ed51

Browse files
authored
Create Media.js
1 parent 8c54b27 commit 401ed51

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

converters/Media.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
const ffmpeg = require('fluent-ffmpeg');
2+
const ffmpegStatic = require('ffmpeg-static');
3+
4+
ffmpeg.setFfmpegPath(ffmpegStatic);
5+
6+
class MediaConverter {
7+
convert(inputPath, outputPath, targetFormat) {
8+
return new Promise((resolve, reject) => {
9+
const cmd = ffmpeg(inputPath);
10+
11+
this._applyOptions(cmd, targetFormat);
12+
13+
cmd
14+
.output(outputPath)
15+
.on('end', resolve)
16+
.on('error', err => reject(new Error(err.message)))
17+
.run();
18+
});
19+
}
20+
21+
_applyOptions(cmd, targetFormat) {
22+
switch (targetFormat) {
23+
case 'mp3':
24+
cmd.audioCodec('libmp3lame').audioBitrate('192k').noVideo();
25+
break;
26+
case 'wav':
27+
cmd.audioCodec('pcm_s16le').noVideo();
28+
break;
29+
case 'flac':
30+
cmd.audioCodec('flac').noVideo();
31+
break;
32+
case 'aac':
33+
cmd.audioCodec('aac').audioBitrate('192k').noVideo();
34+
break;
35+
case 'ogg':
36+
cmd.audioCodec('libvorbis').audioBitrate('192k').noVideo();
37+
break;
38+
case 'm4a':
39+
cmd.audioCodec('aac').audioBitrate('192k').outputOptions('-movflags', '+faststart').noVideo();
40+
break;
41+
case 'mp4':
42+
cmd.videoCodec('libx264').audioCodec('aac').outputOptions('-crf', '23', '-preset', 'fast', '-movflags', '+faststart');
43+
break;
44+
case 'avi':
45+
cmd.videoCodec('libxvid').audioCodec('libmp3lame');
46+
break;
47+
case 'mkv':
48+
cmd.videoCodec('libx264').audioCodec('aac').outputOptions('-crf', '23', '-preset', 'fast');
49+
break;
50+
case 'mov':
51+
cmd.videoCodec('libx264').audioCodec('aac').outputOptions('-crf', '23');
52+
break;
53+
case 'webm':
54+
cmd.videoCodec('libvpx-vp9').audioCodec('libopus').outputOptions('-crf', '30', '-b:v', '0');
55+
break;
56+
default:
57+
throw new Error(`Unsupported media format: ${targetFormat}`);
58+
}
59+
}
60+
}
61+
62+
module.exports = new MediaConverter();

0 commit comments

Comments
 (0)