Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import * as fs from 'fs';
import * as ffmpeg from 'fluent-ffmpeg';
class VideoConvertService {
public connection: any;
public PATH: string = 'videos';
public async saveVideoToMachine(bannerSetId: string, videoBinaryString: any, extention: string, encoding: string = 'utf-8'): Promise<any> {
const filename = bannerSetId;
const path: string = `${this.PATH}/${filename}.${extention}`;
return new Promise((resolve: any, reject: any) => {
fs.writeFile(path, videoBinaryString, { encoding }, function handleWriteWebmFile(err: any) {
if (err) {
console.log(err);
reject(err);
} else {
console.log('gelukt', { path, filename, });
resolve({ path, filename, });
}
});
});
}
public async convert({ filename, inputFormat, outputFormat }: any) {
return new Promise((resolve, reject) => {
const inputPath = `${this.PATH}/${filename}.${inputFormat}`;
const outputPath = `${this.PATH}/${filename}.${outputFormat}`;
ffmpeg()
.input(inputPath)
.inputFormat(inputFormat)
.toFormat(outputFormat)
.saveToFile(outputPath)
.inputOption('anullsrc=r=48000:cl=mono')
.on('codecData', function (data) {
console.log('Input is ' + data.audio + ' audio ' +
'with ' + data.video + ' video');
})
.on('stderr', function (stderrLine) {
console.log('Stderr output: ' + stderrLine);
})
.on('error', function (err, stdout, stderr) {
console.log('Cannot process video: ' + err.message);
return reject(err);
})
.on('end', function (stdout, stderr) {
console.log('Transcoding succeeded !');
return resolve({
path: outputPath,
filename: `${filename}.${outputFormat}`,
});
});
});
}
public async convertMp4ToWebm(filename: string) {
return this.convert({
filename,
inputFormat: 'mp4',
outputFormat: 'webm'
});
}
public async convertWebmToMP4(filename: string) {
return this.convert({
filename,
inputFormat: 'webm',
outputFormat: 'mp4'
});
}
}
export default new VideoConvertService();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment