Skip to content

Instantly share code, notes, and snippets.

@burakaksoy
Last active September 23, 2024 14:36
Show Gist options
  • Select an option

  • Save burakaksoy/2b42ceec73b42b7c9084af37cb84c0a8 to your computer and use it in GitHub Desktop.

Select an option

Save burakaksoy/2b42ceec73b42b7c9084af37cb84c0a8 to your computer and use it in GitHub Desktop.
A Quick video speedup bash script for ALL mp4 files in a directory using 'mencoder'
#!/bin/bash
# Speed Up All Videos Script using ffmpeg
# This script speeds up all .mp4 video files in the current directory using ffmpeg.
# By default, the output videos will have no sound.
#
# Install:
# sudo apt install ffmpeg
#
# Save this script as: speedup_all_videos.sh
#
# Make it executable with:
# chmod +x speedup_all_videos.sh
#
# Usage examples:
# ./speedup_all_videos.sh 6 # Speeds up all videos by 6x, no sound
# ./speedup_all_videos.sh 6 --audio # Speeds up all videos and audio by 6x, pitch changes
# ./speedup_all_videos.sh 6 --audio --keep-pitch # Speeds up all videos and audio by 6x, keeps original pitch
#
# Idea is based on: https://superuser.com/q/160432/1461742
# Check if at least 1 argument was provided
if [ "$#" -lt 1 ]; then
echo "Usage: $0 <speed_scale> [--audio] [--keep-pitch]"
exit 1
fi
# Parse arguments
speed_scale="$1"
audio=false
keep_pitch=false
shift 1
while (( "$#" )); do
case "$1" in
--audio)
audio=true
shift
;;
--keep-pitch)
keep_pitch=true
shift
;;
*)
echo "Unknown option: $1"
echo "Usage: $0 <speed_scale> [--audio] [--keep-pitch]"
exit 1
;;
esac
done
# Check if there are any .mp4 files in the current directory
shopt -s nullglob
mp4_files=(*.mp4 *.avi *.mkv)
if [ ${#mp4_files[@]} -eq 0 ]; then
echo "No .mp4 or .avi or .mkv files found in the current directory."
exit 1
fi
# Loop through all .mp4 files in the current directory
for input_file in "${mp4_files[@]}"; do
# Extract filename without extension
filename=$(basename -- "$input_file")
extension="${filename##*.}"
filename="${filename%.*}"
# Construct output filename
output_file="${filename}-${speed_scale}x.${extension}"
if [ "$audio" = false ]; then
# No audio
ffmpeg -i "$input_file" -filter:v "setpts=PTS/$speed_scale" -an "$output_file"
else
if [ "$keep_pitch" = true ]; then
# Speed up audio but keep pitch
# Calculate inverse of speed_scale
inv_speed=$(echo "1/$speed_scale" | bc -l)
ffmpeg -i "$input_file" -filter_complex \
"[0:v]setpts=PTS/$speed_scale[v]; \
[0:a]asetrate=44100*$speed_scale,aresample=44100,atempo=$inv_speed[a]" \
-map "[v]" -map "[a]" "$output_file"
else
# Speed up audio with pitch change
if (( $(echo "$speed_scale < 0.5" | bc -l) )); then
echo "Error: atempo filter supports values between 0.5 and 100"
exit 1
fi
ffmpeg -i "$input_file" -filter_complex \
"[0:v]setpts=PTS/$speed_scale[v]; \
[0:a]atempo=$speed_scale[a]" \
-map "[v]" -map "[a]" "$output_file"
fi
fi
echo "Output file created: $output_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment