File size: 1,565 Bytes
a65e95e
 
dd77f63
a65e95e
 
dd77f63
a65e95e
5dfc565
 
a65e95e
 
 
 
 
 
 
 
 
 
 
 
5dfc565
 
a65e95e
 
dd77f63
5dfc565
dd77f63
a65e95e
 
 
 
 
 
dd77f63
a65e95e
 
dd77f63
 
 
 
5dfc565
dd77f63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { promises as fs } from "node:fs"
import path from "node:path"

import tmpDir from "temp-dir"
import { v4 as uuidv4 } from "uuid"

import ffmpeg from "fluent-ffmpeg"
import { pendingFilesDirFilePath } from "../config.mts"
import { moveFile } from "../utils/moveFile.mts"

export const addAudioToVideo = async (
  videoFileName: string,
  audioFileName: string,

  /*
  * 0.0: mute the audio completely
  * 0.5: set the audio to 50% of original volume (half volume)
  * 1.0: maintain the audio at original volume (100% of original volume)
  * 2.0: amplify the audio to 200% of original volume (double volume - might cause clipping)
  */
  volume: number = 1.0
) => {
  const tempOutputFilePath = path.join(tmpDir, `${uuidv4()}.mp4`)
  const audioFilePath = path.resolve(tmpDir, audioFileName)

  await new Promise((resolve, reject) => {
    ffmpeg(videoFileName)
      .input(audioFilePath)
      .audioFilters({ filter: 'volume', options: volume }) // add audio filter for volume
      .outputOptions("-c:v copy")  // use video copy codec
      .outputOptions("-c:a aac")   // use audio codec
      .outputOptions("-map 0:v:0") // map video from 0th to 0th
      .outputOptions("-map 1:a:0") // map audio from 1st to 0th
      .outputOptions("-shortest") // finish encoding when shortest input stream ends
      .output(tempOutputFilePath)
      .on("end", resolve)
      .on("error", reject)
      .run()
  })

  // Now we want to replace the original video file with the new file that has been created
  await moveFile(tempOutputFilePath, videoFileName)
};