-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfluent-ffmpeg.js
96 lines (89 loc) · 3.17 KB
/
fluent-ffmpeg.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('ffmpeg-static');
const path = require('path');
const fs = require('fs')
// Set the path to the ffmpeg binary
ffmpeg.setFfmpegPath(ffmpegPath);
function getFileSize(filePath) {
if (fs.existsSync(filePath)) {
const stats = fs.statSync(filePath);
return (stats.size / (1024 * 1024)).toFixed(2); //Convert bytes to MB
} else {
return 'File not found';
}
}
// Function to convert AVI to MP4
function convertAviToMp4(inputPath, outputPath) {
console.time('convertAviToMp4')
return new Promise((resolve, reject) => {
ffmpeg(inputPath)
.output(outputPath)
.on('end', () => {
console.log(`Conversion to MP4 completed. Original file size: ${getFileSize(inputPath)} MB. Converted file size: ${getFileSize(outputPath)} MB`);
console.timeEnd(`convertAviToMp4`)
resolve();
})
.on('error', (err) => {
console.error('Error during conversion:', err);
reject(err);
})
.run();
});
}
// Function to extract a frame at a specific time
function extractFrame(inputPath, outputImagePath, timeInSeconds) {
console.time('extractFrame')
return new Promise((resolve, reject) => {
ffmpeg(inputPath)
.screenshots({
timestamps: [timeInSeconds],
filename: path.basename(outputImagePath),
folder: path.dirname(outputImagePath),
})
.on('end', () => {
console.log('Frame extraction completed.');
console.timeEnd('extractFrame')
resolve();
})
.on('error', (err) => {
console.error('Error during frame extraction:', err);
reject(err);
});
});
}
// Function to compress a video
function compressVideo(inputPath, outputPath) {
console.time('compressVideo')
return new Promise((resolve, reject) => {
ffmpeg(inputPath)
.outputOptions([
'-vcodec libx264',
'-crf 28', // Constant Rate Factor for quality control
])
.output(outputPath)
.on('end', () => {
console.log(`Video compression completed. Original file size: ${getFileSize(inputPath)} MB. Converted file size: ${getFileSize(outputPath)} MB.`);
console.timeEnd('compressVideo')
resolve();
})
.on('error', (err) => {
console.error('Error during compression:', err);
reject(err);
})
.run();
});
}
// Example usage
(async () => {
const inputVideo = 'input.avi';
const convertedVideo = 'output.mp4';
const frameImage = 'frame_at_5s.png';
const compressedVideo = 'compressed_output.mp4';
try {
await convertAviToMp4(inputVideo, convertedVideo);
await extractFrame(convertedVideo, frameImage, 5); // Extract frame at 5 seconds
await compressVideo(convertedVideo, compressedVideo);
} catch (error) {
console.error('An error occurred:', error);
}
})();