使用ffmpeg在python中获取视频持续时间

OSK*_*OSK 6 python video ffmpeg

我在我的电脑上使用pip ffprobe命令安装了ffprobe,并从这里安装了ffmpeg .

但是,我仍然无法运行此处列出的代码.

我尝试使用以下代码失败.

SyntaxError:第12行的文件GetVideoDurations.py中的非ASCII字符'\ xe2',但未声明编码; 有关详细信息,请参阅 http://python.org/dev/peps/pep-0263/

有谁知道什么是错的?我没有正确引用目录吗?我是否需要确保.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)
Run Code Online (Sandbox Code Playgroud)

如果问题有些基本,请道歉.我所需要的只是能够迭代一组视频文件并获得他们的开始时间和结束时间.

谢谢!

Jor*_*rgu 12

使用 ffmpeg-python 包(https://pypi.org/project/ffmpeg-python/)

import ffmpeg
duration = ffmpeg.probe(local_file_path)["format"]["duration"]
Run Code Online (Sandbox Code Playgroud)

其中local_file_path是文件的相对或绝对路径。


Cha*_*ath 10

没有必要迭代输出FFprobe.有一个简单的命令只导致输入文件的持续时间.

ffprobe -i input_audio -show_entries format=duration -v quiet -of csv="p=0"
Run Code Online (Sandbox Code Playgroud)

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

def getLength(input_video):
    result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = result.communicate()
    return output[0]
Run Code Online (Sandbox Code Playgroud)

您还需要提供每个文件的绝对路径.

希望这可以帮助!

  • 第二行应该是`result = subprocess.Popen(['ffprobe -i%s -show_entries format = duration -v quiet -of csv =“ p = 0”'%input_video],stdout = subprocess.PIPE,stderr = subprocess .STDOUT)`,如果没有方括号,则会出现错误。 (2认同)

Kal*_*ien 9

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

Chamath给出的答案非常接近,但最终失败了.

就像一张纸条,我正在使用Python 3.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)
Run Code Online (Sandbox Code Playgroud)

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

def get_duration(file):
Run Code Online (Sandbox Code Playgroud)

至:

def get_duration(self, file):
Run Code Online (Sandbox Code Playgroud)

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

  • 不推荐`shell=True` (2认同)