Last active
November 24, 2024 18:50
-
-
Save ivazin/c19e3e34d4ed5cf804eec16e4d45a0bb to your computer and use it in GitHub Desktop.
Script to export all audio tracks from MKV to separate files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if ffmpeg is installed | |
if ! command -v ffmpeg &> /dev/null; then | |
echo "Error: ffmpeg is not installed. Please install it and try again." | |
exit 1 | |
fi | |
# Input file and output directory | |
INPUT_FILE="$1" | |
OUTPUT_DIR="$2" | |
# Validate input arguments | |
if [[ -z "$INPUT_FILE" || -z "$OUTPUT_DIR" ]]; then | |
echo "Usage: $0 <input_file.mp4> <output_directory>" | |
exit 1 | |
fi | |
# Check if input file exists | |
if [[ ! -f "$INPUT_FILE" ]]; then | |
echo "Error: Input file '$INPUT_FILE' not found." | |
exit 1 | |
fi | |
# Create output directory if it doesn't exist | |
mkdir -p "$OUTPUT_DIR" | |
# Get the base name of the input file (without extension) | |
BASE_NAME=$(basename "$INPUT_FILE" .mp4) | |
# Get the total number of audio tracks in the input file | |
TRACKS=$(ffmpeg -i "$INPUT_FILE" 2>&1 | grep "Stream" | grep "Audio" | wc -l) | |
if [[ $TRACKS -eq 0 ]]; then | |
echo "No audio tracks found in the input file." | |
exit 1 | |
fi | |
echo "Found $TRACKS audio track(s). Extracting..." | |
# Loop through each audio track and extract it | |
for ((i=0; i<TRACKS; i++)); do | |
OUTPUT_FILE="${OUTPUT_DIR}/${BASE_NAME}-audio-$((i + 1)).m4a" | |
echo "Extracting audio track $((i + 1)) to $OUTPUT_FILE..." | |
ffmpeg -i "$INPUT_FILE" -map "0:a:$i" -c:a aac -b:a 192k -y "$OUTPUT_FILE" &> /dev/null | |
if [[ $? -eq 0 ]]; then | |
echo "Track $((i + 1)) extracted successfully." | |
else | |
echo "Failed to extract track $((i + 1))." | |
fi | |
done | |
echo "Extraction complete. Files saved to '$OUTPUT_DIR'." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment