Skip to content

Instantly share code, notes, and snippets.

@realies
Created October 12, 2023 15:32
Show Gist options
  • Save realies/45d654f0a94a16da534b5f248d536ba6 to your computer and use it in GitHub Desktop.
Save realies/45d654f0a94a16da534b5f248d536ba6 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const { exec, execSync } = require('child_process');
const getStartTime = (fileName) => {
const ffprobeOutput = execSync(`ffprobe -v quiet -print_format json -show_entries format=start_time ${fileName}`).toString();
const ffprobeJSON = JSON.parse(ffprobeOutput);
return parseFloat(ffprobeJSON.format.start_time) * 1000;
};
const mixAudioTracks = (audioFiles) => {
let aresampleFilters = [];
let amixInputs = [];
const referenceStartTime = Math.min(...audioFiles.map(file => file.startTime));
audioFiles.forEach((file, index) => {
const delay = file.startTime - referenceStartTime;
if (delay > 0) {
aresampleFilters.push(`[${index}]aresample=async=1,adelay=${delay}|${delay}[a${index}]`);
} else {
aresampleFilters.push(`[${index}]aresample=async=1[a${index}]`);
}
amixInputs.push(`[a${index}]`);
});
const filterComplex = `${aresampleFilters.join('; ')}; ${amixInputs.join('')}amix=inputs=${audioFiles.length}[audio]`;
const inputFiles = audioFiles.map(file => `-acodec libopus -i ${file.name}`).join(' ');
const ffmpegCommand = `ffmpeg ${inputFiles} -filter_complex "${filterComplex}" -map [audio] -acodec libopus output.mka`;
console.log({ffmpegCommand});
exec(ffmpegCommand, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing ffmpeg: ${error}`);
return;
}
console.log(`ffmpeg stdout: ${stdout}`);
console.log(`ffmpeg stderr: ${stderr}`);
});
};
const main = () => {
const dirPath = '.';
const fileNames = fs.readdirSync(dirPath).filter(fileName => fileName.endsWith('.mka'));
const audioFiles = fileNames.map(fileName => ({ name: fileName, startTime: getStartTime(fileName) }));
mixAudioTracks(audioFiles);
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment