Certainly! Below is a Python script that fulfills your requirements on Ubuntu 22.04. This script:
- Scans a specified directory for all audio and video files with common extensions.
- Calculates the duration of each media file using
ffprobe (part of the ffmpeg suite).
- Sums up the total duration of all media files.
- Sorts the media files from longest to shortest duration.
- Saves the sorted list (filename and duration) to a
.txt file.
- Prints the total duration to the terminal.
Prerequisites
- Python 3 installed on your system. Most Ubuntu installations come with Python 3 pre-installed. You can verify by running:
python3 --version
- ffmpeg installed, which includes
ffprobe. To install ffmpeg, run:
sudo apt update
sudo apt install ffmpeg
Python Script
Save the following script as media_duration.py:
#!/usr/bin/env python3
import os
import subprocess
import argparse
from datetime import timedelta
def get_media_duration(file_path):
"""
Uses ffprobe to get the duration of a media file in seconds.
"""
try:
# Run ffprobe command to get duration
result = subprocess.run(
[
"ffprobe",
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
file_path
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
duration = float(result.stdout.strip())
return duration
except Exception as e:
print(f"Error retrieving duration for {file_path}: {e}")
return 0.0
def format_timedelta(seconds):
"""
Converts seconds to H:MM:SS format.
"""
return str(timedelta(seconds=int(seconds)))
def main():
# Set up command-line argument parsing
parser = argparse.ArgumentParser(description="Aggregate durations of media files.")
parser.add_argument("directory", help="Path to the directory containing media files.")
parser.add_argument("-o", "--output", default="media_list.txt", help="Output .txt file name.")
args = parser.parse_args()
# Define common media file extensions
media_extensions = {
'.mp3', '.wav', '.aac', '.flac', '.ogg', '.wma', '.m4a',
'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm'
}
media_files = []
total_duration = 0.0
# Walk through the directory recursively
for root, dirs, files in os.walk(args.directory):
for file in files:
ext = os.path.splitext(file)[1].lower()
if ext in media_extensions:
file_path = os.path.join(root, file)
duration = get_media_duration(file_path)
media_files.append((file_path, duration))
total_duration += duration
# Sort media files by duration in descending order
media_files_sorted = sorted(media_files, key=lambda x: x[1], reverse=True)
# Write sorted media files to the output .txt file
try:
with open(args.output, 'w') as f:
for file, duration in media_files_sorted:
formatted_duration = format_timedelta(duration)
f.write(f"{file}\t{formatted_duration}\n")
print(f"Media list saved to {args.output}")
except Exception as e:
print(f"Error writing to {args.output}: {e}")
return
# Print the total duration
formatted_total = format_timedelta(total_duration)
print(f"Total Duration: {formatted_total}")
if __name__ == "__main__":
main()
Making the Script Executable
First, ensure the script has executable permissions. Open your terminal and navigate to the directory containing media_duration.py, then run:
chmod +x media_duration.py
Using the Script
Run the script by specifying the target directory. You can also optionally specify the output .txt filename using the -o flag.
Basic Usage:
./media_duration.py /path/to/your/media/directory
Specifying an Output File:
./media_duration.py /path/to/your/media/directory -o my_media_list.txt
Script Explanation
-
Import Statements:
os, subprocess, and argparse handle file system operations, run external commands, and parse command-line arguments, respectively.
timedelta from datetime is used to format the total duration into a readable format.
-
get_media_duration Function:
- Utilizes
ffprobe to extract the duration of a media file.
- Returns the duration in seconds as a floating-point number.
-
format_timedelta Function:
- Converts seconds into a
H:MM:SS formatted string for readability.
-
main Function:
- Parses command-line arguments for the target directory and optional output filename.
- Defines a set of common media file extensions to search for.
- Walks through the specified directory recursively, identifying media files based on their extensions.
- Retrieves the duration of each media file and accumulates the total duration.
- Sorts the list of media files from longest to shortest duration.
- Writes the sorted list (with durations) to the specified
.txt file.
- Prints the total duration to the terminal.
Sample Output
After running the script, you might see output similar to:
Media list saved to media_list.txt
Total Duration: 10:35:20
Your media_list.txt will contain entries like:
/path/to/media/movie1.mkv 02:15:30
/path/to/media/song2.mp3 05:45
/path/to/media/video3.mp4 01:30:50
...
Notes
- Performance Consideration: For directories with a large number of media files, the script might take some time to process as it calls
ffprobe for each file.
- Error Handling: The script prints an error message if it fails to retrieve the duration of any media file but continues processing the rest.
- Extensibility: You can add or remove media file extensions in the
media_extensions set within the script as needed.
Alternative: Bash Script
If you prefer using a Bash script instead of Python, here's an alternative approach leveraging ffprobe and standard UNIX utilities.
Save the following as media_duration.sh:
#!/bin/bash
# Check if directory is provided
if [ -z "$1" ]; then
echo "Usage: $0 /path/to/media/directory"
exit 1
fi
DIRECTORY="$1"
OUTPUT_FILE="media_list.txt"
# Define media extensions
EXTENSIONS=("mp3" "wav" "aac" "flac" "ogg" "wma" "m4a" "mp4" "avi" "mkv" "mov" "wmv" "flv" "webm")
# Initialize total duration
TOTAL_DURATION=0
# Temporary file to store durations
TEMP_FILE=$(mktemp)
# Find and process media files
for ext in "${EXTENSIONS[@]}"; do
find "$DIRECTORY" -type f -iname "*.$ext" -print0 | while IFS= read -r -d '' file; do
# Get duration in seconds using ffprobe
duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file")
duration=${duration%.*} # Truncate to integer
echo -e "$duration\t$file" >> "$TEMP_FILE"
TOTAL_DURATION=$((TOTAL_DURATION + duration))
done
done
# Sort the temporary file by duration descending and write to output
sort -nr "$TEMP_FILE" > sorted_media.txt
# Convert durations to H:MM:SS and write to final output
> "$OUTPUT_FILE"
while IFS=$'\t' read -r duration file; do
# Convert seconds to H:MM:SS
printf -v hms "%02d:%02d:%02d" $((duration/3600)) $(( (duration%3600)/60 )) $((duration%60))
echo -e "${file}\t${hms}" >> "$OUTPUT_FILE"
done < sorted_media.txt
# Cleanup temporary files
rm "$TEMP_FILE" sorted_media.txt
# Convert total duration to H:MM:SS
printf -v total_hms "%02d:%02d:%02d" $((TOTAL_DURATION/3600)) $(( (TOTAL_DURATION%3600)/60 )) $((TOTAL_DURATION%60))
echo "Total Duration: $total_hms"
echo "Media list saved to $OUTPUT_FILE"
Make the script executable:
chmod +x media_duration.sh
Run the script:
./media_duration.sh /path/to/your/media/directory
Explanation:
- The script searches for media files with specified extensions.
- It uses
ffprobe to get the duration of each file in seconds.
- Durations and file paths are stored in a temporary file.
- The list is sorted in descending order based on duration.
- The sorted list is formatted into
H:MM:SS and saved to the output .txt file.
- Finally, the script prints the total duration.
Note: Bash scripts might be less efficient for processing a very large number of files compared to Python, but they are perfectly suitable for smaller datasets and simpler use cases.
Feel free to choose the approach that best fits your comfort and requirements. If you encounter any issues or have further questions, feel free to ask!