如何在特定视频的第二秒钟将背景音乐添加到视频文件?在节点流利的ffmpeg

时间:2019-06-03 20:13:16

标签: node.js ffmpeg

我有一个12秒长的audio.mp3文件 video.mp4的时长为60秒。

我需要在视频的第40秒上插入audio.mp3。

如何使用node-fluent-ffmpeg做到这一点?

1 个答案:

答案 0 :(得分:0)

我住在乌克兰,我不太会英语,所以我才意识到这一点。 这些是可以添加到类中的异步方法,我想您会理解的本质

// just variables
let cutesAudio = await this.cutAudio(audio, time, tempAudio);
let videoDuration = await this.getMediaDuration(video);
let mergeVideoAudio = await this.margeFiles(cutesAudio, video, tempVideo);
let cutMergeVideo = await this.cuteVideo(mergeVideoAudio, videoDuration, resultVideo);


 // cut audio from a specific time and get temp.mp3
 async cutAudio (audio, time, outputMp3) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .input(audio)
      .setStartTime(time)
      .output(outputMp3)
      .format('mp3')
      .on('end', () => {                    
          resolve(outputMp3);
      }).on('error', (_err) => {
        reject(_err);
      }).run();
   });
 }

 // get the video duration
 async getMediaDuration (file) {
   return new Promise((resolve, reject) => {
      ffmpeg.ffprobe(file, (_err, metadata) => {
        if (_err === null) {
          resolve(metadata.format.duration);
        } else {
          reject(_err);
        }
      });
   });
 } 


 // connect the cut off temp.mp3 and the video and get temp.mp4
 async margeFiles (audio, video, outputVideo) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .videoCodec('libx264')
      .format('mp4')
      .outputFormat('mp4')
      .input(audio)
      .input(video)
      .output(outputVideo)
      .on('end', () => {                    
          resolve(outputVideo);
      }).on('error', (_err) => {
          reject(_err);
      }).run();
   });
 }

 // we cut off the video we make it old length as the music can be longer.
 async cuteVideo (video, time, result) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .input(video)
      .setDuration(time)
      .format('mp4')
      .output(result)
      .on('end', () => {                    
          resolve(result);
      }).on('error', (_err) => {
        reject(_err);
      }).run();
   });
 }