Skip to content

Instantly share code, notes, and snippets.

@crischutu07
Last active May 19, 2025 06:19
Show Gist options
  • Save crischutu07/4f00b51c17d13f0a15479aa680e4628d to your computer and use it in GitHub Desktop.
Save crischutu07/4f00b51c17d13f0a15479aa680e4628d to your computer and use it in GitHub Desktop.
convert audio to video using bash script with ffmpeg
#!/usr/bin/env bash
# Author: crischutu07
# Usage: audio2mp4.sh <audio.mp3> [output.mp4] [cover.jpeg]
# NOTE: albumimg variable is temporary
if [ -f "$3" ]; then
basefilename=$(basename -- "$3")
if [[ ! $basefilename =~ .*\.(jpg|jpeg) ]]; then
ffmpeg -i "$3" "${basefilename%.*}.jpg" || {
echo "Failed to convert non-jpeg file to jpeg!"
exit 2
} &&
albumimg="${basefilename%.*}.jpg"
else
albumimg="$3"
fi
unset basefilename
else
# embedded album cover in audio files tend to use
# JPEG format.
albumimg="$(mktemp --suffix=.jpg)"
fi
audio="$1"
output="$2"
if [ ! -f "$audio" ]; then
echo "Requires an input file (Highly recommend using 'opus' or 'mp3' audio file for MP4!)"
exit 1
elif [[ ! $audio =~ .*\.(mp3|wav|opus|flac|ogg|m4a|aac|3gp|oga|mogg|webm|aiff) ]]; then
echo "Not an audio file."
exit 1
fi
if [ -z "$output" ]; then
basefilename="$(basename -- "$audio")"
output="${basefilename%.*}.mp4"
echo "No file output! Defaulting to: ${output}"
unset basefilename
fi
if [ ! -f "$3" ]; then
ffmpeg -i "$audio" \
-an \
-vf "scale=1024:-1" \
"$albumimg" -y || {
echo -e "Failed to run FFmpeg, make sure the audio file contains embedded album cover.\nOr manually specify it by running:\n=> $(basename -- "$0") \"$1\" \"$output\" cover.jpg (Where 'cover.jpg' is the album cover!)"
[ -z "$3" ] && rm "$albumimg"
exit 1
}
fi
ffmpeg -loop 1 \
-i "$albumimg" \
-i "$audio" \
-c:a copy \
-c:v libx264 \
-profile:v high \
-preset ultrafast \
-map_metadata 1 \
-ac 2 \
-crf 20 \
-pix_fmt yuv420p \
-tune stillimage \
-r 15 \
-shortest \
-y "$output"
[ -z "$3" ] && rm "$albumimg"
read -r -p "Save option (catbox,open,delete): " saveoption
case "$saveoption" in
catbox) if command catbox; then
catbox file "$output"
else
echo "You don't have catbox installed on PATH."; exit 2
fi;;
open) termux-open "$output" && exit 0;;
delete) rm "$output" && echo "Deleted $output"; exit 0;;
*) exit 0;;
esac
unset output albumimg audio output saveoption
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment