通过Python脚本运行ffmpeg命令

1 投票
6 回答
7736 浏览
提问于 2025-04-18 00:43

我正在尝试在Python中执行ffmpeg命令。

当我在Windows的命令行中执行以下命令时,它是可以正常工作的:

C:\FFmpeg\bin\ffmpeg -rtbufsize 100000k -r 65535/2733 -f dshow -i audio="virtual-audio-capturer":video="screen-capture-recorder" output100.avi

但是当我试着用这种方式在Python中运行这个命令时:

cmd='C:\FFmpeg\bin\ffmpeg -rtbufsize 100000k -r 65535/2733 -f dshow -i audio="virtual-audio-capturer":video="screen-capture-recorder" output100.avi'
subprocess.call(cmd, shell=true)

它就不行了。

我也试过这种方式:

cmd='C:\FFmpeg\bin\ffmpeg -rtbufsize 100000k -r 65535/2733 -f dshow -i audio="virtual-audio-capturer":video="screen-capture-recorder" output100.avi'
subprocess.check_call(cmd) 

但也没有成功。

我想知道我哪里做错了。我使用的是Python 2.76。谢谢。

6 个回答

0

试试这个:

import os
os.system(cmd)

根据我的了解,这种方法没有subprocess那么高级,但它能完成它应该做的事情。

0

出现 Windowserror:[Error 2] 的原因是因为 shell=False 的错误。

如果你在运行命令时把 cmd 当作字符串传入,那么你必须使用 shell=True

cmd='C:\FFmpeg\bin\ffmpeg -rtbufsize 100000k -r 65535/2733 -f dshow -i audio="virtual-audio-capturer":video="screen-capture-recorder" output100.avi'
subprocess.check_call(cmd, shell=True)

如果你不使用 shell=True,那么你需要把 cmd 作为列表传入:

cmd='C:\FFmpeg\bin\ffmpeg -rtbufsize 100000k -r 65535/2733 -f dshow -i audio="virtual-audio-capturer":video="screen-capture-recorder" output100.avi'
subprocess.check_call([cmd])

以上的说法对于 Popen 和 check_call 函数都是一样的。

0

没有错误信息,我无法判断具体情况,但大多数文档都说在调用这个程序时要用“ffmpeg.exe”作为可执行文件。另外,你可以把参数放在一个列表里,然后传递进去:

没有测试过

import subprocess as sp

def get_ffmpeg_bin():
    ffmpeg_dir = "C:\\FFmpeg\\bin\\ffmpeg"
    FFMPEG_BIN = os.path.join(ffmpeg_dir, "ffmpeg.exe")
    return FFMPEG_BIN


pipe = sp.Popen([ffmpeg_binary, "-rtbufsize", "100000k", "-r", "65535/2733", "-f", "dshow", "-i", 'audio="virtual-audio-capturer":video="screen-capture-recorder"', "output100.avi"])

pipe.wait()
1

这是一篇旧帖子,但我觉得今天仍然很有用。我成功地让它运行起来,所以想和大家分享一下。

我的视频文件超过3个小时(3:09:09),我只想从中提取出一个特定的画面,时间是20分钟17秒(20:17),并保存为一张图片。所以这里是可以用的代码(在Windows 10,64位,Python 3.7上测试过):

import os
#Input video file
in_video=r"C:\temp\tu\my-trip-on-the-great-wall.rmvb"
#Output image file
out_image=r"C:\Users\rich_dad\Documents\test2.jpg"

#ffmpeg installation path
appDir=r"c:\ffmpeg\bin"

#Change directory on the go
os.chdir(appDir)

#Execute command
os.system("ffmpeg -ss 20:17 -i "+in_video+" -vframes 1 -q:v 2 "+out_image)

如果我需要从视频中提取更多照片,我肯定会在这个代码里加一个循环。我希望你们觉得这个有用。

2

我想把一些电影文件转换成音频文件,但在Python中使用ffmpeg时遇到了问题,直到我明确地包含了文件路径,像这样:

import os

Executable = r'C:\Users\rrabcdef\Documents\p\apps\ffmpeg\ffmpeg.exe'
input = r'C:\Users\rrabcdef\Documents\p\myStuff\clip_1.mov'
output = r'C:\Users\rrabcdef\Documents\p\myStuff\clip_1.mp3'
myCommand = Executable + " -i " + input + " -f mp3 -ab 320000 -vn " + output
os.system(myCommand)

撰写回答