Skip to content

Instantly share code, notes, and snippets.

@aminya
Created November 15, 2021 20:00
Show Gist options
  • Save aminya/2aeba7b274a8396a75c370e517e8f29f to your computer and use it in GitHub Desktop.
Save aminya/2aeba7b274a8396a75c370e517e8f29f to your computer and use it in GitHub Desktop.
Batch replace audio in video files
# This uses ffmpeg https://www.ffmpeg.org/
# modify the video and audio extensions if needed
mkdir -p output
foreach ($video in (ls *.mp4)) {
$video_name = ($video).Name;
$audio_name = $video_name.replace('.mp4', '.mp3');
ffmpeg -i $video_name -i $audio_name -c copy -map 0:v:0 -map 1:a:0 "output/$video_name"
# the above is based on https://superuser.com/a/1137613/1006010
# If the audio is longer than the video, you will want to add -shortest before the output file name.
# Using -c:v copy instead of -c copy means to copy the video only, and re-encoding the audio. -c copy will copy both the video and audio without re-encoding.
# -map 0:v:0 maps the first (index 0) video stream from the input to the first (index 0) video stream in the output.
# -map 1:a:0 maps the second (index 1) audio stream from the input to the first (index 0) audio stream in the output.
# Not specifying an audio codec, will automatically select a working one. You can specify one by for example adding -c:a libvorbis after -c:v copy. You can also use -c copy to avoid re-encoding the audio, but this has lead to compatibility and synchronization problems in my past.
}
@chabb7312
Copy link

How to use this, please

@chabb7312
Copy link

How to run it.

@aminya
Copy link
Author

aminya commented Jul 10, 2023

@chabb7312
Download the file and copy it to the folder that has the videos and audios. They should have the same name. Then open Powershell. Go to the path that has the files:

cd "C:/path_to_folder

Then run

./batch_audio_replace.ps1

You need to install ffmpeg and put on your Path too
https://www.ffmpeg.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment