Skip to content

Instantly share code, notes, and snippets.

@yinyanfr
Last active September 1, 2023 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinyanfr/4cbf93a328abaa7b8e06e5d2bcd4ad40 to your computer and use it in GitHub Desktop.
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.
#!/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