fluent-ffmpeg 如何让视频渲染与代码同步?

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

我只想在 ffmpeg 完成视频渲染后才制作代码 运行。目前,代码比视频渲染速度快 运行s。

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");

控制台显示:

Fully Completed
Video 0 rendered
Video 1 rendered

执行应该相反。如何让代码在继续之前等待视频完成渲染?

下面的代码可以帮到您:

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)
        })
    })
}

for of 循环是唯一能够等待 async await 的循环。