Sure! Below is a robust and well-documented Zsh script designed for macOS. This script processes an output.mp4 file containing consolidated music tracks, detects the start and end times of each song based on silence detection, and outputs the timings alongside the corresponding song titles in the MM:SS Song Title format.
Prerequisites:
- FFmpeg: Ensure that FFmpeg is installed on your Mac. You can install it using Homebrew with the following command:
brew install ffmpeg
Script Overview:
- Check Dependencies and Input File: The script verifies the presence of
ffmpeg and the output.mp4 file.
- Define Song List: An array contains all the song titles in the order they appear in the MP4.
- Extract Total Duration: Retrieves the total duration of the MP4 file.
- Detect Silence: Uses FFmpeg's
silencedetect filter to find silence periods indicating song boundaries.
- Parse Silence Data: Processes the FFmpeg output to identify silence start and end times.
- Determine Song Segments: Calculates the start and end times for each song based on silence detection.
- Assign Song Titles: Maps each detected segment to the corresponding song title.
- Output Results: Prints the start and end times along with song titles in the specified format.
Zsh Script:
#!/bin/zsh
# Exit immediately if a command exits with a non-zero status.
set -e
# Function to print error messages to stderr
error() {
echo "Error: $1" >&2
}
# Function to convert seconds to MM:SS format
format_time() {
local total_seconds=$1
local minutes=$((total_seconds / 60))
local seconds=$((total_seconds % 60))
printf "%02d:%02d" "$minutes" "$seconds"
}
# Check if ffmpeg is installed
if ! command -v ffmpeg >/dev/null 2>&1; then
error "ffmpeg is not installed. Please install it using Homebrew: brew install ffmpeg"
exit 1
fi
# Input MP4 file
INPUT_FILE="output.mp4"
# Check if the input file exists
if [[ ! -f "$INPUT_FILE" ]]; then
error "Input file '$INPUT_FILE' not found in the current directory."
exit 1
fi
# Define the list of songs
songs=(
"Cineris Somnia"
"Ivy"
"Daydream"
"Dust and Light"
"Swaying Daisy"
"Garden of Light"
"The White Box"
"Waiting by the Windowsill"
"Charlotte's Theme"
"The White Box-Broken"
"A Warm Room"
"Charlotte's Theme-Wither"
"Wild Rose"
"Marie's Theme"
"Deep Forest"
"Mist"
"Night Carol"
"False Blue"
"Death of the Little Bird"
"Ophelia's Theme-Darkness"
"Hall of Silence"
"Downstairs"
"Black Insanity"
"Judgment"
"Decaying Corridor"
"Pandora's Box"
"Ophelia's Theme-Light"
"Under Cloudy Skies"
"Tender Black"
"Neverending Dream"
"Angel's Lament"
"World of Ashes"
"Cineris Somnia - Alone In The Ashes"
"Cineris Somnia - PV Version"
"Cineris Somnia - Fragile"
)
# Get total duration of the input file in seconds (with decimals)
total_duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$INPUT_FILE")
# Convert to integer seconds
total_duration_seconds=${total_duration%.*}
# Temporary file to store silencedetect logs
TEMP_FILE=$(mktemp)
# Ensure the temporary file is deleted on exit
trap 'rm -f "$TEMP_FILE"' EXIT
# Run ffmpeg with silencedetect and capture stderr
ffmpeg -i "$INPUT_FILE" -af silencedetect=noise=-30dB:d=1 -f null "$INPUT_FILE" 2> "$TEMP_FILE"
# Initialize arrays to hold silence start and end times
silence_starts=()
silence_ends=()
# Parse the ffmpeg silencedetect output
while IFS= read -r line; do
if [[ $line =~ silence_start:\ ([0-9]+\.[0-9]+) ]]; then
silence_starts+=("${match[1]}")
elif [[ $line =~ silence_end:\ ([0-9]+\.[0-9]+)\ | ]]; then
silence_ends+=("${match[1]}")
fi
done < "$TEMP_FILE"
# Ensure that for every silence_end there is a corresponding silence_start
# If not, handle the last silence_end
if (( ${#silence_ends[@]} < ${#silence_starts[@]} )); then
# Assume the last silence_end is the start of last silence until end
silence_ends+=("$total_duration")
fi
# Initialize song segments
# Each segment will be a tuple: (start_time, end_time)
segments=()
# Start with the first song starting at 0
current_start=0
# Iterate through silence_starts and silence_ends to define song segments
for i in {1..${#silence_starts[@]}}; do
silence_start=${silence_starts[i-1]}
silence_end=${silence_ends[i-1]}
# Define the end of the current song as the silence_start
current_end=${silence_start%.*} # Convert to integer seconds
segments+=("$current_start,$current_end")
# Next song starts after the silence ends
current_start=${silence_end%.*}
done
# Add the last segment from the last silence_end to total_duration
segments+=("$current_start,$total_duration_seconds")
# Check if the number of segments matches the number of songs
if (( ${#segments[@]} != ${#songs[@]} )); then
error "Number of detected song segments (${#segments[@]}) does not match the number of songs (${#songs[@]})."
exit 1
fi
# Output the start and end times with song titles
echo "Detected Song Timings:"
echo "----------------------"
for i in {1..${#segments[@]}}; do
segment=(${segments[i-1]//,/ })
start_sec=${segment[1]}
end_sec=${segment[2]}
start_formatted=$(format_time "$start_sec")
end_formatted=$(format_time "$end_sec")
echo "${start_formatted} - ${end_formatted} ${songs[i-1]}"
done
How to Use the Script:
-
Save the Script: Copy the script above into a file named process_songs.zsh.
-
Make the Script Executable:
chmod +x process_songs.zsh
-
Place output.mp4 in the Same Directory: Ensure that your output.mp4 file is in the same directory as the script.
-
Run the Script:
./process_songs.zsh
Script Output:
The script will output a list of songs with their corresponding start and end times in the MM:SS - MM:SS Song Title format. For example:
Detected Song Timings:
----------------------
00:00 - 02:15 Cineris Somnia
02:15 - 04:30 Ivy
04:30 - 06:45 Daydream
...
Notes and Best Practices:
-
Silence Detection Parameters: The silencedetect filter uses noise=-30dB and d=1 (1 second). You may need to adjust these parameters (noise threshold and duration) based on the actual audio characteristics to improve accuracy.
-
Error Handling: The script includes checks to ensure that the number of detected segments matches the number of songs. If there's a mismatch, it will notify you and exit gracefully.
-
Temporary Files: The script uses a temporary file to store FFmpeg logs and ensures it's deleted upon script exit, even if an error occurs.
-
Time Conversion: The format_time function converts seconds to a MM:SS format, ignoring fractional seconds for simplicity.
-
Extensibility: You can modify the songs array to match your specific list of song titles if they change.
-
FFmpeg Installation: If FFmpeg isn't installed, the script provides a clear error message guiding you to install it via Homebrew.
This script should provide a solid foundation for processing your consolidated music MP4 file and extracting the desired timings for each song. Adjust the silence detection parameters as needed to fit the nuances of your specific audio file.