答案 0 :(得分:39)
您可能需要调用外部程序。 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]
答案 1 :(得分:16)
为了使事情更容易一些,以下代码将输出放到 JSON 。
您可以使用probe(filename)
来使用它,或使用duration(filename)
获取持续时间:
json_info = probe(filename)
secondes_dot_ = duration(filename) # float number of seconds
它适用于安装Ubuntu 14.04
的{{1}}。代码没有针对速度或美观目的进行优化,但它可以在我的机器上运行,希望它有所帮助。
ffprobe
答案 2 :(得分:14)
据此报道https://www.reddit.com/r/moviepy/comments/2bsnrq/is_it_possible_to_get_the_length_of_a_video/
你可以使用moviepy模块
from moviepy.editor import VideoFileClip
clip = VideoFileClip("my_video.mp4")
print( clip.duration )
答案 3 :(得分:7)
( 2020年答案)
解决方案:
opencv
0.0065秒✔ffprobe
0.0998秒moviepy
2.8239秒✔ OpenCV 方法:
def with_opencv(filename):
import cv2
video = cv2.VideoCapture(filename)
duration = video.get(cv2.CAP_PROP_POS_MSEC)
frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
return duration, frame_count
用法: print(with_opencv('my_video.webm'))
其他:
ffprobe
方法:
def with_ffprobe(filename):
import subprocess, json
result = subprocess.check_output(
f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"',
shell=True).decode()
fields = json.loads(result)['streams'][0]
duration = fields['tags']['DURATION']
fps = eval(fields['r_frame_rate'])
return duration, fps
moviepy
方法:
def with_moviepy(filename):
from moviepy.editor import VideoFileClip
clip = VideoFileClip(filename)
duration = clip.duration
fps = clip.fps
width, height = clip.size
return duration, fps, (width, height)
答案 4 :(得分:5)
找到这个新的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)
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 :(得分:3)
如此处报道 https://www.reddit.com/r/moviepy/comments/2bsnrq/is_it_possible_to_get_the_length_of_a_video/
您可以使用moviepy模块
from moviepy.editor import VideoFileClip clip = VideoFileClip("my_video.mp4") print( clip.duration )
如果您尝试在一个文件夹中获取许多视频的时长,则会崩溃并显示错误消息: AttributeError:“ AudioFileClip”对象没有属性“ reader”
因此,为了避免这种情况,您需要添加
clip.close()
基于此: https://zulko.github.io/moviepy/_modules/moviepy/video/io/VideoFileClip.html
所以代码看起来像这样:
from moviepy.editor import VideoFileClip
clip = VideoFileClip("my_video.mp4")
print( clip.duration )
clip.close()
干杯! :)
答案 7 :(得分:1)
对https://github.com/kkroening/ffmpeg-python(tf.TensorSpec.from_tensor(tensor)
)使用现代方法。别忘了也安装pip install ffmpeg-python --user
。
获取视频信息:
ffmpeg
使用import ffmpeg
info=ffmpeg.probe(filename)
print(f"duration={info['format']['duration']}")
print(f"framerate={info['streams'][0]['avg_frame_rate']}")
包还可以轻松地创建,编辑过滤器并将其应用于视频。
答案 8 :(得分:0)
打开cmd终端并使用此命令安装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"))
答案 9 :(得分:0)
对于喜欢使用 mediainfo 程序的任何人:
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
答案 10 :(得分:0)
我想到的一个功能。这基本上是使用仅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
答案 11 :(得分:0)
上面的pymediainfo答案确实帮助了我。谢谢。
作为一个初学者,确实花了一些时间来找出丢失的内容(以及如何以其他方式处理属性)(请参见下文)。
出现以下示例:
# sudo apt install mediainfo
# pip3 install pymediainfo
from pymediainfo import MediaInfo
media_info = MediaInfo.parse('/home/pi/Desktop/a.mp4')
for track in media_info.tracks:
#for k in track.to_data().keys():
# print("{}.{}={}".format(track.track_type,k,track.to_data()[k]))
if track.track_type == 'Video':
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("{} width {}".format(track.track_type,track.to_data()["width"]))
print("{} height {}".format(track.track_type,track.to_data()["height"]))
print("{} duration {}s".format(track.track_type,track.to_data()["duration"]/1000.0))
print("{} duration {}".format(track.track_type,track.to_data()["other_duration"][3][0:8]))
print("{} other_format {}".format(track.track_type,track.to_data()["other_format"][0]))
print("{} codec_id {}".format(track.track_type,track.to_data()["codec_id"]))
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
elif track.track_type == 'Audio':
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("{} format {}".format(track.track_type,track.to_data()["format"]))
print("{} codec_id {}".format(track.track_type,track.to_data()["codec_id"]))
print("{} channel_s {}".format(track.track_type,track.to_data()["channel_s"]))
print("{} other_channel_s {}".format(track.track_type,track.to_data()["other_channel_s"][0]))
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("********************************************************************")
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Video width 1920
Video height 1080
Video duration 383.84s
Video duration 00:06:23
Video other_format AVC
Video codec_id avc1
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Audio format AAC
Audio codec_id mp4a-40-2
Audio channel_s 2
Audio other_channel_s 2 channels
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
答案 12 :(得分:0)
在函数中使用ffprobe,它以秒为单位返回视频的持续时间。
def video_duration(filename):
import subprocess
secs = subprocess.check_output(f'ffprobe -v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 "{filename}"', shell=True).decode()
return secs