如何在不下载完整视频的情况下获取在线视频的时长?

6
为了获取视频的持续时间和分辨率,我有以下函数:
def getvideosize(url, verbose=False):
try:
    if url.startswith('http:') or url.startswith('https:'):
        ffprobe_command = ['ffprobe', '-icy', '0', '-loglevel', 'repeat+warning' if verbose else 'repeat+error', '-print_format', 'json', '-select_streams', 'v', '-show_streams', '-timeout', '60000000', '-user-agent', BILIGRAB_UA, url]
    else:
        ffprobe_command = ['ffprobe', '-loglevel', 'repeat+warning' if verbose else 'repeat+error', '-print_format', 'json', '-select_streams', 'v', '-show_streams', url]
    logcommand(ffprobe_command)
    ffprobe_process = subprocess.Popen(ffprobe_command, stdout=subprocess.PIPE)
    try:
        ffprobe_output = json.loads(ffprobe_process.communicate()[0].decode('utf-8', 'replace'))
    except KeyboardInterrupt:
        logging.warning('Cancelling getting video size, press Ctrl-C again to terminate.')
        ffprobe_process.terminate()
        return 0, 0
    width, height, widthxheight, duration = 0, 0, 0, 0
    for stream in dict.get(ffprobe_output, 'streams') or []:
        if dict.get(stream, 'duration') > duration:
            duration = dict.get(stream, 'duration')
        if dict.get(stream, 'width')*dict.get(stream, 'height') > widthxheight:
            width, height = dict.get(stream, 'width'), dict.get(stream, 'height')
    if duration == 0:
        duration = 1800
    return [[int(width), int(height)], int(float(duration))+1]
except Exception as e:
    logorraise(e)
    return [[0, 0], 0]

但是有些在线视频没有 duration 标签。我们能做些什么来获取它的持续时间吗?


通常不可能。在许多情况下,持续时间信息不容易获得(需要实际媒体解析)或位于文件末尾。 - 9dan
3个回答

11
如果你有视频本身的直接链接,例如http://www.dl.com/xxx.mp4,你可以使用ffprobe来获取该视频的持续时间:
ffprobe -i some_video_direct_link -show_entries format=duration -v quiet -of csv="p=0"

3
import cv2
data = cv2.VideoCapture('https://v.buddyku.id/ugc/m3YXvl-61837b3d8a0706e1ee0ab139.mp4')
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = int(data.get(cv2.CAP_PROP_FPS))
seconds = int(frames / fps)
print("duration in seconds:", seconds)

2

我知道这个问题很老了,但是有一种更好的方法来解决它。

通过将einverne的答案与一些实际的Python代码(在本例中为Python 3.5)相结合,我们可以创建一个简短的函数,返回视频中的秒数(持续时间)。

import subprocess

def get_duration(file):
    """Get the duration of a video using ffprobe."""
    cmd = ['ffprobe', '-i', file, '-show_entries', 'format=duration',
           '-v', 'quiet', '-of', 'csv="p=0"']
    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    output = float(output)
    return round(output)

调用该函数的方法如下:

video_length_in_seconds = get_duration('/path/to/your/file') # mp4, avi, etc

这将给你总秒数,四舍五入到最接近的整秒。所以如果你的视频是30.6秒,这将返回31
FFMpeg命令ffprobe -i video_file_here -show_entries format=duration -v quiet -of csv="p=0"将为您获取视频持续时间,并不应下载整个视频。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接