Skip to content

Instantly share code, notes, and snippets.

@kane-thornwyrd
Created February 1, 2025 11:49
Show Gist options
  • Save kane-thornwyrd/4a4dbf3a4bbcc727331421c99453ce82 to your computer and use it in GitHub Desktop.
Save kane-thornwyrd/4a4dbf3a4bbcc727331421c99453ce82 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Display help message if the script is called with "-h" or without parameters.
if [[ "$1" == "-h" || -z "$1" ]]; then
echo "Usage: $0 <file_path> [target_directory] < timestamps_file"
echo "
Description:
This script splits a media file into parts based on timestamps read from a file.
Arguments:
<file_path> Path to the input media file to be split.
[target_directory] Optional. Path to the directory where the split parts will be saved.
If not provided, the parts are saved in the same directory as the input file.
How it works:
- Provide a list of timestamps (one per line) via a file using input redirection.
- The script directly uses 'ffmpeg' to split the file at the specified timestamps.
Supported formats:
- Video: MP4, MKV, AVI, MOV, WMV, FLV, and others supported by ffmpeg.
- Audio: MP3, AAC, WAV, FLAC, OGG, M4A, and others supported by ffmpeg.
Example:
$0 video.mp4 /path/to/target_directory < timestamps.txt"
exit 0
fi
readarray -t ts < /dev/stdin
path=$1
fn=${1##*/}
dir=${path%$fn}
name=${fn%.*}
ext=${fn#$name}
target_dir=${2:-$dir}
# Ensure the target directory exists
if [[ ! -d "$target_dir" ]]; then
mkdir -p "$target_dir"
fi
# Determine if the input is audio or video based on the MIME type
mime_type=$(file --mime-type -b "$path")
if [[ "$mime_type" == audio/* ]]; then
echo "Input file is detected as an audio file."
elif [[ "$mime_type" == video/* ]]; then
echo "Input file is detected as a video file."
else
echo "Warning: Unable to determine file type. Proceeding with ffmpeg."
fi
# Loop through the timestamps and process the splits with ffmpeg
for ((i=1; i<${#ts[@]}; i++)); do
printf -v part '%02d' "$i"
output_file="$target_dir/$name-$part$ext"
echo "Processing segment $part: ${ts[i-1]} to ${ts[i]}"
ffmpeg -y -loglevel error -ss "${ts[i-1]}" -to "${ts[i]}" -i "$path" "$output_file"
if [[ $? -ne 0 ]]; then
echo "Error: Failed to process segment $part"
exit 1
fi
echo "Segment $part saved to $output_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment