Search code examples
pythonvideo

How to get the duration of a video in Python?


I need to get the duration of a video in Python. The video formats that I need to get are MP4, Flash video, AVI, and MOV... I have a shared hosting solution, so I have no FFmpeg support.

What would you suggest?

Thanks!


Solution

  • You can use the external command ffprobe for this. Specifically, run this bash command from the FFmpeg Wiki:

    import subprocess
    
    def get_length(filename):
        result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
                                 "format=duration", "-of",
                                 "default=noprint_wrappers=1:nokey=1", filename],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
        return float(result.stdout)