Using ffmpeg to obtain video durations in python

后端 未结 7 1092
故里飘歌
故里飘歌 2020-12-10 06:46

I\'ve installed ffprobe using the pip ffprobe command on my PC, and installed ffmpeg from here.

However, I\'m still having trouble running the code listed here.

7条回答
  •  暖寄归人
    2020-12-10 07:13

    I'd suggest using FFprobe (comes with FFmpeg).

    The answer Chamath gave was pretty close, but ultimately failed for me.

    Just as a note, I'm using Python 3.5 and 3.6 and this is what worked for me.

    import subprocess 
    
    def get_duration(file):
        """Get the duration of a video using ffprobe."""
        cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'.format(file)
        output = subprocess.check_output(
            cmd,
            shell=True, # Let this run in the shell
            stderr=subprocess.STDOUT
        )
        # return round(float(output))  # ugly, but rounds your seconds up or down
        return float(output)
    

    If you want to throw this function into a class and use it in Django (1.8 - 1.11), just change one line and put this function into your class, like so:

    def get_duration(file):
    

    to:

    def get_duration(self, file):
    

    Note: Using a relative path worked for me locally, but the production server required an absolute path. You can use os.path.abspath(os.path.dirname(file)) to get the path to your video or audio file.

提交回复
热议问题