edpse
edpse

Reputation: 31

How to add background music to a video file on a specific video second? In node-fluent-ffmpeg

I have a 12sec long audio.mp3 file and video.mp4 is 60sec long.

I need to insert audio.mp3 on the 40th second of the video.

How to do it with node-fluent-ffmpeg?

Upvotes: 1

Views: 1196

Answers (1)

edpse
edpse

Reputation: 31

I live in Ukraine and I do not know English well, that's how I realized it. These are asynchronous methods that can be added to the class, I think you will understand the essence

// 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();
   });
 }

Upvotes: 1

Related Questions