Skip to content

Instantly share code, notes, and snippets.

@tomfbush
Last active April 29, 2025 11:02
Show Gist options
  • Select an option

  • Save tomfbush/01227dd103c8ace66ac2f5d62af6bf26 to your computer and use it in GitHub Desktop.

Select an option

Save tomfbush/01227dd103c8ace66ac2f5d62af6bf26 to your computer and use it in GitHub Desktop.
Convert a directory of mp4 videos into smaller webm videos, preserving audio tracks where present
#!/bin/bash
# Set the target height for the output videos
TARGET_HEIGHT=720
# Loop through all files in the current directory
for file in *; do
# Check if the file is an MP4 video (you can extend this to other formats if needed)
if [[ "$file" =~ \.mp4$ ]]; then
# Get the filename without the extension
filename_no_ext="${file%.*}"
# Construct the output filename
output_file="${filename_no_ext}_reduced.webm"
# Use ffprobe to check for audio streams
audio_streams=$(ffprobe -v error -show_entries stream=codec_type -of default=noprint_wrappers=1:nokey=1 "$file" | grep audio | wc -l)
# Print a message to the user
echo "Processing: $file"
echo "Outputting: $output_file"
# Construct the ffmpeg command. Include "-an" only if no audio streams are found.
if [ "$audio_streams" -eq 0 ]; then
ffmpeg_cmd="ffmpeg -i \"$file\" -an -c:v libvpx-vp9 -crf 30 -b:v 0 -vf scale=-1:$TARGET_HEIGHT -preset medium \"$output_file\""
echo "No audio stream found. Removing audio."
else
ffmpeg_cmd="ffmpeg -i \"$file\" -c:v libvpx-vp9 -crf 30 -b:v 0 -vf scale=-1:$TARGET_HEIGHT -preset medium \"$output_file\""
echo "Audio stream(s) found. Keeping audio."
fi
# Execute the ffmpeg command
eval "$ffmpeg_cmd"
# Check if the conversion was successful
if [ $? -eq 0 ]; then
echo "Conversion successful."
else
echo "Conversion failed."
fi
else
echo "Skipping: $file (not an MP4 file)"
fi
done
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment