nodejs中使用fluent-ffmpeg实现n个webm视频文件先转码在合并

时间:2024-01-30 07:52:51
1.引入fluent-ffmpeg
 
var ffmpeg = require(\'fluent-ffmpeg\');
 

2.将n个webm文件重新编码 ,输入为“_i.webm”为 “i.webm”

function runFFmpegWebmS(roomId,length) {
    for(var i=0;i<length;i++){
        runFFmpegWebm(roomId,i,length);
    }
}

  

function runFFmpegWebm(roomId,i,length) {
    var fileName1 = path.join(__dirname, \'uploads\',\'\'+roomId,\'webm\',\'_\'+i+\'.webm\').replace(/\\/g,\'/\');
    var fileName2 = path.join(__dirname, \'uploads\',\'\'+roomId,\'webm\',i+\'.webm\').replace(/\\/g,\'/\');
    ffmpeg(fileName1)
    .output(fileName2)
    .on(\'end\', function() {
        console.log(\'视频转码Finished processing\');
        console.log("i:"+i+",length:"+length)
        if(i==length-1){  //这一步判断比较关键,当最后一个webm文件编码完成后调用合并的函数
            console.log("视频转码全部完成");
            runFFmpegCombine_Webm(roomId,length);
        }
    })
    .run();
}

  

3.将新生成的n个webm视频文件合并

function runFFmpegCombine_Webm(roomId,length) {
    var file =path.join(__dirname, \'uploads\',\'\'+roomId,\'webm\',\'0.webm\').replace(/\\/g,\'/\');
    var outPath = path.join(__dirname, \'uploads\',\'\'+roomId,\'webm\',roomId+\'.webm\').replace(/\\/g,\'/\');
    try{
        var proc = ffmpeg(file);
        for(var i=1;i<length;i++){
            proc=proc.input(path.join(__dirname, \'uploads\',\'\'+roomId,\'webm\',i+\'.webm\').replace(/\\/g,\'/\'));
        }
        proc.mergeToFile(outPath).on(\'end\', function() {
            console.log(\'视频合并成功\');
        });
        }catch(err){
        console.log( \'an error occured!\',err );
    } 
}