Skip to content

Instantly share code, notes, and snippets.

@tytydraco
Created October 8, 2022 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tytydraco/41e9788f48a2f5fa196571946fc3c73a to your computer and use it in GitHub Desktop.
Save tytydraco/41e9788f48a2f5fa196571946fc3c73a to your computer and use it in GitHub Desktop.
Convert audio to OPUS format from a WEBM or other container.
#!/usr/bin/env bash
# Ignore SIGINT.
trap '' SIGINT
# Given a file name, get the audio codec.
get_codec_name() {
ffprobe "$1" \
-v quiet \
-show_streams \
-select_streams a \
-show_entries stream=codec_name \
| grep codec_name \
| awk -F'=' '{ print $2 }' \
|| exit 1
}
file_path="$1"
file_name="$(basename -- "$file_path")"
file_name_no_ext="${file_name%.*}"
codec_name="$(get_codec_name "$file_path")"
parent_dir="$(dirname "$file_path")"
new_path="$parent_dir/$file_name_no_ext.opus"
[[ -f "$new_path" ]] && exit 0
# By default, extract audio and remove video stream.
ffmpeg_args=("-x" "-vn")
# If the audio stream is already opus, and we aren't messing with the audio,
# just copy the stream.
if [[ "$codec_name" == "opus" ]] && [[ "$mode" != "d" ]]; then
ffmpeg_args+=("-acodec" "copy")
fi
# If we want to downscale the audio, reduce it to 16 kbps.
[[ "$mode" == "d" ]] && ffmpeg_args+=("-b:a" "16k")
echo -e "\e[36m[PROCESSING]\e[0m $file_name"
# Fork to background to ignore SIGINT.
setsid -w ffmpeg \
-hide_banner \
-nostats \
-nostdin \
-v error \
-i "$file_path" \
"${ffmpeg_args[@]}" \
-- \
"$new_path" \
|| exit 1 &
# Wait for FFMPEG.
wait
# Clean up.
rm "$file_path"
echo -e "\e[32m[DONE]\e[0m $file_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment