Created
October 12, 2023 15:32
-
-
Save realies/45d654f0a94a16da534b5f248d536ba6 to your computer and use it in GitHub Desktop.
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
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