使用Python中的FFmpeg获取视频时长

2024-04-20 00:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在我的PC上使用pip ffprobe命令安装了ffprobe,并从here安装了ffmpeg。

但是,我仍然无法运行列出的代码here

我试图使用以下代码失败。

SyntaxError: Non-ASCII character '\xe2' in file GetVideoDurations.py on line 12, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

有人知道怎么了吗?我没有正确地引用目录吗?我是否需要确保.py和视频文件位于特定位置?

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]

fileToWorkWith = ‪'C:\Users\PC\Desktop\Video.mkv'

getLength(fileToWorkWith)

如果这个问题有点基本,请道歉。我所需要的只是能够遍历一组视频文件并获得它们的开始时间和结束时间。

谢谢你!


Tags: 代码inpyforherestdout时间result
3条回答

我认为查马斯的第二条评论回答了这个问题:你的剧本中有一个奇怪的字符,要么是因为你用了一个“而不是a”,要么是因为你有一个带有非英语口音的单词,就像这样。

作为一个注释,对于您正在做的事情,您还可以尝试MoviePy,它可以像您一样解析ffmpeg输出(但也许将来我将使用Chamath的ffprobe方法,它看起来更干净):

import moviepy.editor as mp
duration =  mp.VideoFileClip("my_video.mp4").duration

我建议使用FFprobe(附带FFmpeg)。

查马斯给出的答案非常接近,但最终对我来说失败了。

如前所述,我使用的是Python3.5和3.6,这对我很有用。

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)

如果你想把这个函数放到一个类中,并在Django(1.8-1.11)中使用它,只需改变一行,然后把这个函数放到你的类中,如下所示:

def get_duration(file):

致:

def get_duration(self, file):

注意:使用相对路径在本地对我有效,但生产服务器需要绝对路径。您可以使用os.path.abspath(os.path.dirname(file))获取视频或音频文件的路径。

无需遍历FFprobe的输出。有one simple command只返回输入文件的持续时间:

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 <input_video>

您可以使用以下方法来获取持续时间:

def get_length(input_video):
    result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_video], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return float(result.stdout)

相关问题 更多 >