Skip to content

Instantly share code, notes, and snippets.

@markpbaggett
Last active April 19, 2024 19:36
Show Gist options
  • Save markpbaggett/690b50dfb9d5f27c6d5d0e3c0f5d8404 to your computer and use it in GitHub Desktop.
Save markpbaggett/690b50dfb9d5f27c6d5d0e3c0f5d8404 to your computer and use it in GitHub Desktop.
import os
from moviepy.editor import VideoFileClip
import subprocess
class DurationCalculator:
def __init__(self, file_path):
self.audio_types = ('.mp3')
self.video_types = ('mp4', 'mov', 'm4v', 'dv')
self.file_path = file_path
self.details = self.crawl()
self.total_duration = self.calculate_total_duration(self.details[0])
self.audio_duration = self.calculate_total_duration(self.details[2])
@staticmethod
def calculate_total_duration(all_durations):
return sum(all_durations) / 60 / 60
def crawl(self):
video_durations = []
audio_durations = []
video_files = []
audio_files = []
for root, dirs, files in os.walk(self.file_path):
for file in files:
file_extension = file.split('.')[-1]
try:
if file_extension in self.video_types:
current_path = os.path.join(root, file)
video_durations.append(self.get_duration(current_path))
video_files.append(current_path)
if file_extension in self.audio_types:
current_path = os.path.join(root, file)
audio_durations.append(self.get_duration(current_path))
audio_files.append(current_path)
except KeyError:
print(f"Error with {file}")
return video_durations, video_files, audio_durations, audio_files
@staticmethod
def get_duration(path):
clip = VideoFileClip(path)
return clip.duration
@staticmethod
def get_audio_duration(audio_file):
result = subprocess.run(['ffprobe', '-i', audio_file, '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return float(result.stdout)
if __name__ == "__main__":
dc = DurationCalculator("/vhosts/trace/web/assets")
print(dc.total_duration)
print(dc.audio_duration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment