Skip to content

Instantly share code, notes, and snippets.

@manasmbellani
Last active April 22, 2022 04:55
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 manasmbellani/0a2229d0ed2782c346fe599b07d8c1a2 to your computer and use it in GitHub Desktop.
Save manasmbellani/0a2229d0ed2782c346fe599b07d8c1a2 to your computer and use it in GitHub Desktop.
ffmpeg_extract_audio_between_times.sh - Extract audio/video between times via ffmpeg
#!/bin/bash
if [ $# -lt 3 ]; then
echo "[-] $0 $action <in-video-audio-file> <start-time-as-HH:MM:SS> <end-time-as-HH:MM:SS/num_seconds> [out-file]"
exit
fi
in_audio_file="$1"
start_time="$2"
end_time_num_seconds="$3"
if [ -z "$out_file" ]; then
in_file_ext="${in_audio_file##*.}"
in_file_name_without_ext="${in_audio_file%.*}"
out_file=`echo "$in_file_name_without_ext""_modified.$in_file_ext"`
fi
echo "[+] out_file: $out_file"
if [ ! -f "$in_audio_file" ]; then
echo "[-] File: $in_audio_file not found."
exit
fi
if [ ! -z `echo "$end_time_num_seconds" | grep ":"` ]; then
end_time="$end_time_num_seconds"
hh_end=`echo "$end_time" | cut -d":" -f1 | sed 's/^0//'`
mm_end=`echo "$end_time" | cut -d":" -f2 | sed 's/^0//'`
ss_end=`echo "$end_time" | cut -d":" -f3 | sed 's/^0//'`
hh_st=`echo "$start_time" | cut -d":" -f1 | sed 's/^0//'`
mm_st=`echo "$start_time" | cut -d":" -f2 | sed 's/^0//'`
ss_st=`echo "$start_time" | cut -d":" -f3 | sed 's/^0//'`
echo "[*] $hh_end,$mm_end,$ss_end $hh_st,$mm_st,$ss_st"
num_seconds=$(( (hh_end-hh_st)*3600 + (mm_end-mm_st)*60 + (ss_end-ss_st) ))
if [ "$num_seconds" -lt 0 ]; then
echo "[-] End time must be before start time. num_seconds: $num_seconds < 0."
exit
fi
else
num_seconds="$end_time_num_seconds"
fi
echo "[+] num_seconds: $num_seconds"
echo "[*] Extracting audio between start time: $start_time and num_seconds: $num_seconds"
yes | ffmpeg -i "$in_audio_file" -ss "$start_time" -t "$num_seconds" -acodec copy "$out_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment