代码之家  ›  专栏  ›  技术社区  ›  eos87

如何在python中获取视频的持续时间?

  •  26
  • eos87  · 技术社区  · 15 年前

    我需要用python获取视频持续时间。我需要的视频格式是 MP4 ,Flash视频, AVI 和移动…我有一个共享的托管解决方案,所以我没有 FFmpeg 支持。

    8 回复  |  直到 15 年前
        1
  •  40
  •   Peter Mortensen Pieter Jan Bonestroo    14 年前

    您可能需要调用一个外部程序。 ffprobe 可以向您提供以下信息:

    import subprocess
    
    def getLength(filename):
      result = subprocess.Popen(["ffprobe", filename],
        stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
      return [x for x in result.stdout.readlines() if "Duration" in x]
    
        2
  •  16
  •   Andrew_1510    10 年前

    为了使事情简单一点,下面的代码将输出 杰森 .

    你可以用它 probe(filename) 或通过使用获取持续时间 duration(filename) :

    json_info     = probe(filename)
    secondes_dot_ = duration(filename) # float number of seconds
    

    它工作在 Ubuntu 14.04 当然在哪 ffprobe 安装。代码并不是为了速度或漂亮的目的而优化的,但它在我的机器上工作,希望它能有所帮助。

    #
    # Command line use of 'ffprobe':
    #
    # ffprobe -loglevel quiet -print_format json \
    #         -show_format    -show_streams \
    #         video-file-name.mp4
    #
    # man ffprobe # for more information about ffprobe
    #
    
    import subprocess32 as sp
    import json
    
    
    def probe(vid_file_path):
        ''' Give a json from ffprobe command line
    
        @vid_file_path : The absolute (full) path of the video file, string.
        '''
        if type(vid_file_path) != str:
            raise Exception('Gvie ffprobe a full file path of the video')
            return
    
        command = ["ffprobe",
                "-loglevel",  "quiet",
                "-print_format", "json",
                 "-show_format",
                 "-show_streams",
                 vid_file_path
                 ]
    
        pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT)
        out, err = pipe.communicate()
        return json.loads(out)
    
    
    def duration(vid_file_path):
        ''' Video's duration in seconds, return a float number
        '''
        _json = probe(vid_file_path)
    
        if 'format' in _json:
            if 'duration' in _json['format']:
                return float(_json['format']['duration'])
    
        if 'streams' in _json:
            # commonly stream 0 is the video
            for s in _json['streams']:
                if 'duration' in s:
                    return float(s['duration'])
    
        # if everything didn't happen,
        # we got here because no single 'return' in the above happen.
        raise Exception('I found no duration')
        #return None
    
    
    if __name__ == "__main__":
        video_file_path = "/tmp/tt1.mp4"
        duration(video_file_path) # 10.008
    
        3
  •  11
  •   mobcdi    10 年前

    如本文所述 https://www.reddit.com/r/moviepy/comments/2bsnrq/is_it_possible_to_get_the_length_of_a_video/

    你可以使用电影模块

    from moviepy.editor import VideoFileClip
    clip = VideoFileClip("my_video.mp4")
    print( clip.duration )
    
        4
  •  5
  •   beckert    8 年前

    找到这个新的python库: https://github.com/sbraz/pymediainfo

    要获取持续时间:

    from pymediainfo import MediaInfo
    media_info = MediaInfo.parse('my_video_file.mov')
    #duration in milliseconds
    duration_in_ms = media_info.tracks[0].duration
    

    上面的代码是根据一个有效的MP4文件测试的,可以工作,但是您应该做更多的检查,因为它严重依赖于MediaInfo的输出。

        5
  •  5
  •   DeWil    7 年前
    from subprocess import check_output
    
    file_name = "movie.mp4"
    
    #For Windows
    a = str(check_output('ffprobe -i  "'+file_name+'" 2>&1 |findstr "Duration"',shell=True)) 
    
    #For Linux
    #a = str(check_output('ffprobe -i  "'+file_name+'" 2>&1 |grep "Duration"',shell=True)) 
    
    a = a.split(",")[0].split("Duration:")[1].strip()
    
    h, m, s = a.split(':')
    duration = int(h) * 3600 + int(m) * 60 + float(s)
    
    print(duration)
    
        6
  •  0
  •   Jansen Simanullang Di Zou    8 年前

    打开命令终端,安装python包: mutagen 使用此命令

    python -m pip install mutagen

    然后使用此代码获取视频持续时间及其大小:

    import os
    from mutagen.mp4 import MP4
    
    audio = MP4("filePath")
    
    print(audio.info.length)
    print(os.path.getsize("filePath"))
    
        7
  •  0
  •   vossman77    8 年前

    对于任何喜欢使用 媒体信息 程序:

    import json
    import subprocess
    
    #===============================
    def getMediaInfo(mediafile):
        cmd = "mediainfo --Output=JSON %s"%(mediafile)
        proc = subprocess.Popen(cmd, shell=True,
            stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        data = json.loads(stdout)
        return data
    
    #===============================
    def getDuration(mediafile):
        data = getMediaInfo(mediafile)
        duration = float(data['media']['track'][0]['Duration'])
        return duration
    
        8
  •  0
  •   sr9yar Ayushman Parchoria    7 年前

    我想到的功能。这基本上是在使用 只有 ffprobe 论据

    from subprocess import  check_output, CalledProcessError, STDOUT 
    
    
    def getDuration(filename):
    
        command = [
            'ffprobe', 
            '-v', 
            'error', 
            '-show_entries', 
            'format=duration', 
            '-of', 
            'default=noprint_wrappers=1:nokey=1', 
            filename
          ]
    
        try:
            output = check_output( command, stderr=STDOUT ).decode()
        except CalledProcessError as e:
            output = e.output.decode()
    
        return output
    
    
    fn = '/app/648c89e8-d31f-4164-a1af-034g0191348b.mp4'
    print( getDuration(  fn ) )
    

    输出持续时间如下:

    7.338000