Last active
September 1, 2023 11:03
-
-
Save yinyanfr/4cbf93a328abaa7b8e06e5d2bcd4ad40 to your computer and use it in GitHub Desktop.
Combines .ts video files from a directory or multiple directories into .mp4 files using ffmpeg.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/** | |
* @example node ts-merge.js ./videos output_folder | |
*/ | |
const { execSync } = require("child_process"); | |
const { readdirSync, writeFileSync, existsSync, mkdirSync } = require("fs"); | |
const { join } = require("path"); | |
const [, , inputPath, outputPath] = process.argv; | |
/** | |
* Combines .ts video files from a directory into a single .mp4 output file using ffmpeg. | |
* @param {string} inputPath - Path to the directory containing .ts files. | |
* @param {string} outputPath - Path to the output .mp4 file. | |
*/ | |
function combineTSFiles(inputPath, outputPath) { | |
const ls = readdirSync(inputPath); | |
const tsFiles = ls.filter((e) => e.match(/\.ts$/)); | |
const inputTxt = tsFiles | |
.map((file) => `file '${inputPath}/${file}'`) | |
.join("\n"); | |
writeFileSync(join(__dirname, "input.txt"), inputTxt); | |
const ffmpegArgs = [ | |
"-f", | |
"concat", | |
"-safe", | |
"0", | |
"-i", | |
"input.txt", | |
"-c", | |
"copy", | |
outputPath, | |
]; | |
const cmd = `ffmpeg ${ffmpegArgs.join(" ")}`; | |
const stdout = execSync(cmd); | |
console.log(stdout.toString()); | |
} | |
/** | |
* Combines .ts video files from a directory or multiple directories into .mp4 files. | |
* If the inputPath contains .ts files directly, it combines them into a single .mp4. | |
* If the inputPath contains subdirectories, it processes each subdirectory separately, | |
* combining their .ts files into individual .mp4 files with matching folder names. | |
* @param {string} inputPath - Path to the directory or directories containing .ts files. | |
* @param {string} outputPath - Path to the directory where the .mp4 files will be saved. | |
*/ | |
function combineTSFolders(inputPath, outputPath) { | |
const ls = readdirSync(inputPath); | |
console.log(ls); | |
if (ls.find((e) => e.match(/\.ts$/))) { | |
combineTSFiles(inputPath); | |
} else { | |
if (!existsSync(outputPath)) { | |
mkdirSync(outputPath, { recursive: true }); | |
} | |
for (const folder of ls) { | |
combineTSFiles( | |
join(inputPath, folder), | |
join(outputPath, `${folder}.mp4`) | |
); | |
} | |
} | |
} | |
combineTSFolders(inputPath, outputPath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment