如何在Python中获得video的持续时间?

我需要在Python中获得video的持续时间。 我需要的video格式是MP4 ,Flashvideo, AVI和MOV …我有一个共享的托pipe解决scheme,所以我没有FFmpeg的支持。

你可能需要调用一个外部程序。 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] 

为了使事情变得更容易一些,下面的代码将输出放到JSON中

您可以使用probe(filename)来使用它,或者使用duration(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 

正如这里报告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 ) 

find这个新的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文件进行testing的,但是您应该进行更多的检查,因为它严重依赖于MediaInfo的输出。

打开cmd并使用此命令安装mutgen.mp4 python -m pip install mutagen

然后使用此代码来获取video的持续时间和大小:

 import os from mutagen.mp4 import MP4 audio = MP4("filePath") print(audio.info.length) print(os.path.getsize("filePath"))