Skip to content

Instantly share code, notes, and snippets.

@ericek111
Last active February 20, 2022 01:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericek111/7b10dc5e2fb811e0b019f433da48049d to your computer and use it in GitHub Desktop.
Save ericek111/7b10dc5e2fb811e0b019f433da48049d to your computer and use it in GitHub Desktop.
Stretch/shift and combine audio/video from different sources
#!/bin/bash
# deps: sox, ffmpeg
audiof="$1"
videof="$2"
outputf="$3"
tmp_file="$(mktemp /tmp/stargate.XXXXXXX)"
echo "$!" > "$tmp_file"
audio_tmp="$tmp_file.orig.wav"
shifted_tmp="$tmp_file.shifted.wav"
function myTrapHandler() {
rm "$tmp_file"*
exit 0
}
trap myTrapHandler SIGINT;
if [ "$#" -lt 3 ]; then
echo "Format: $0 (audio file) (video file) (output file)"
exit 1
fi
offset_start=0
offset_end=0
video_dur="$(ffprobe -hide_banner -loglevel error -i "$videof" -select_streams v:0 -show_entries format=duration -v quiet -of csv="p=0")"
audio_dur="$(ffprobe -hide_banner -loglevel error -i "$audiof" -select_streams a:0 -show_entries format=duration -v quiet -of csv="p=0")"
factor="$(echo "$video_dur/($audio_dur+$offset_end)" | bc -l)"
factor_r="$(echo "($audio_dur+$offset_end)/$video_dur" | bc -l)"
echo ">>> Audio: $audio_dur, video: $video_dur, factor of $factor"
echo ">>> Saving audio to $audio_tmp..."
# < /dev/null &> ~/tmp/log.txt
ffmpeg -hide_banner -nostdin -n -loglevel error -i "$audiof" -vn -map 0:a:0 -f wav "$audio_tmp"
echo ">>> Shifting (to $video_dur sec.) $audio_tmp to $shifted_tmp"
#rubberband -L --no-lamination --window-long --detector-soft --centre-focus -D "$video_dur" "$audio_tmp" "$shifted_tmp"
#ffmpeg -hide_banner -loglevel error -f wav -i "$audio_tmp" -filter:a "atempo=$factor_r" -f wav "$shifted_tmp"
soxargs="tempo $factor_r"
if (( $(echo "$offset_start < 0" |bc -l) )); then
soxargs="$soxargs trim ${offset_start#-}"
else
soxargs="$soxargs pad $offset_start@0"
fi
sox "$audio_tmp" "$shifted_tmp" $soxargs
rm "$audio_tmp"
echo ">>> Remuxing...."
if [ -f "$outputf" ]; then
echo "$outputf already exists!"
rm "$shifted_tmp"
rm "$tmp_file"
exit 2
fi
ffmpeg -hide_banner -nostdin -n -loglevel error -i "$videof" -i "$shifted_tmp" -c:v copy -map 0:v:0 -map 1:a:0 -movflags +faststart "$outputf"
rm "$shifted_tmp"
echo ">>> Done! Output: $outputf"
rm "$tmp_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment