You are viewing a single comment's thread from:

RE: LeoThread 2024-10-26 15:20

in LeoFinance7 days ago

2: Main Python Code with Explanation

Here’s the main Python code that lists video files in the current folder, calculates durations, and outputs the combined, average, and median durations in hours:minutes:seconds.fractions format:

# Import necessary modules
import os
import moviepy.editor as mp
import statistics

# Set up list to hold video durations in seconds
video_durations = []

# Define a list of video file extensions for filtering
video_extensions = ['.mp4', '.mov', '.avi', '.mkv']

# Function to convert seconds to "hours:minutes:seconds.fractions" format
def format_duration(seconds):
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = seconds % 60  # remaining seconds with fraction
    return f"{hours}:{minutes:02}:{secs:06.3f}"  # format with leading zeros for minutes, seconds, and fraction
Sort:  
# Get all video files in the current directory
for file in os.listdir('.'):
    # Check if the file is a video file based on its extension
    if any(file.endswith(ext) for ext in video_extensions):
        try:
            # Load the video file and get its duration
            video = mp.VideoFileClip(file)
            duration = video.duration  # Duration in seconds
            video_durations.append(duration)
            video.close()  # Close the file to free up resources
        except Exception as e:
            print(f"Error processing {file}: {e}")
# Calculate total duration, average, and median if there are video files
if video_durations:
    total_duration = sum(video_durations)
    average_duration = total_duration / len(video_durations)
    median_duration = statistics.median(video_durations)

    # Write results to a text file
    with open("video_duration_stats.txt", "w") as f:
        f.write(f"Combined duration of all video files: {format_duration(total_duration)}\n")
        f.write(f"Average duration of video files: {format_duration(average_duration)}\n")
        f.write(f"Median duration of video files: {format_duration(median_duration)}\n")
    print("Video duration stats have been saved to 'video_duration_stats.txt'")
else:
    print("No video files found in the current directory.")