Search code examples
ffmpegasync-awaitfluent-ffmpeg

fluent-ffmpeg How to make video rendering synchronous with code?


I want to make the code run only after ffmpeg has finished rendering the videos. Currently, the code runs faster than the videos can render.

videos.forEach((vid, i) => {
  ffmpeg(`${process.cwd()}/video/tmp/${vid}`)
  .outputOptions(['-r 30', '-filter:v scale=w=720:h=1280', '-crf 20'])
  .save(`${process.cwd()}/video/tmp/${vid}`)
  .on('end', ()=> console.log(`Video ${i} rendered`));
});
console.log("Fully Completed");

The console shows:

Fully Completed
Video 0 rendered
Video 1 rendered

The execution should be opposite. How can I make the code wait for video to finish rendering before continuing?


Solution

  • the code below will help you:

    async function processVideos(){
        let videos = [vid1.mp4, vid2.mp4, vid3.mp4];
        for(vid of videos){
            await processVideoSync(vid)
        }
    }
    function processVideoSync(vid){
        return new Promise((resolve,reject)=>{
           ffmpeg(`${process.cwd()}/video/tmp/${vid}`)
           .outputOptions(['-r 30', '-filter:v scale=w=720:h=1280', '-crf 20'])
           .save(`${process.cwd()}/video/tmp/${vid}`)
           .on('end', ()=>{
              console.log(`Video ${i} rendered`)
              return resolve()
            })
            .on('err',(err)=>{
                return reject(err)
            })
        })
    }
    

    o loop for of é o unico capaz de esperar o async await.