首页 > 解决方案 > converting complex ffmpeg command to python3

问题描述

I have a complicated ffmpeg command that takes audio and image as input, and exports a music video.

ffmpeg -loop 1 -framerate 2 -i "front.png" -i "testWAVfile.wav" \
    -vf "scale=2*trunc(iw/2):2*trunc(ih/2),setsar=1,format=yuv420p" \
    -c:v libx264 -preset medium -tune stillimage \
    -crf 18 -c:a aac -shortest -vf scale=1920:1080  "outputVideo.mp4"

I'm trying to write a python3 program cmdMusicVideo.py which will run this command in pure Python. I know that to run this command you need the ffmpeg program, I'm trying to write it in pure python3, where I'm not just spawning a separate process to run the bash command where the user needs to have ffmpeg installed.

I've looked at the various solutions to running ffmpeg in python3, and they're either:

The pip libraries I've checkout out all use incredibly different formatting, and I haven't found a way to replicate my ffmpeg command. I've searched the loop command in their python package documentation and it doesn't appear anywhere.

Is there a way to convert my ffmpeg command into a python3 program where the user doesn't need to already have ffmpeg installed on their computer?

The plan is to eventually turn this into its own pip package, and my concern is that if I use the A method, there would be a case where somebody tries to run my pip command but doesn't have ffmpeg installed on their terminal (maybe using a python3 specific terminal?)

标签: pythonpython-3.xbashffmpegpip

解决方案


有没有办法将我的 ffmpeg 命令转换为 python3 程序,用户不需要在他们的计算机上安装 ffmpeg?

简短的回答:没有。

计划是最终把它变成自己的 pip 包,我担心的是,如果我使用 A 方法,会出现有人试图运行我的 pip 命令但没有在他们的终端上安装 ffmpeg 的情况(也许使用 python3 特定的终端?)

您应该在安装步骤中添加检查以确保用户/系统ffmpeg在其路径上有二进制文件,如果没有则引发错误(并将用户指向带有 ffmpeg 安装说明的 URL)。没有“最佳”方法可以做到这一点,这取决于您如何让用户安装程序。这里有三个选项。

生成文件

如果您使用的是 Makefile,您可以在 Makefile 的顶部添加如下内容:

ifeq ($(shell which ffmpeg),)
$(error Please install ffmpeg using "apt-get install ffmpeg")
endif

如果未安装二进制文件,这将在运行任何make命令之前失败。ffmpeg

仅 setup.py

如果你只是setup.py单独使用一个没有 Makefile 的文件,你可以在你的顶部添加这样的东西setup.py(在你调用之前setup()):

import subprocess
try:
    subprocess.run(["ffmpeg","--help"], check=True)
except subprocess.CalledProcessError:
    print('Please install ffmpeg using "apt-get install ffmpeg"')

康达

这实际上是 conda 的用例之一,它旨在为用户提供一个简单的工具来安装东西(如 pip),但也能够构建和安装非 Python 二进制文件(与 pip 不同)。可以通过 conda 看到 ffmpeg 可用:

$ conda search ffmpeg
Loading channels: done
# Name                       Version           Build  Channel
ffmpeg                           3.4      h766ddd1_0  pkgs/main
ffmpeg                           3.4      h8a2ae75_0  pkgs/main
ffmpeg                           4.0      h01ea3c9_0  pkgs/main
ffmpeg                           4.0      hc84425e_0  pkgs/main
ffmpeg                           4.2      h677a3f5_0  pkgs/main

因此,您可以创建一个 conda 配方,而不是打包您的程序并使其在 Pypi 上可用。有关详细信息,请参阅创建 conda 配方,但基本上您会在meta.yml文件中指定 ffmpeg 作为要求:

requirements:
  host:
    - ffmpeg 4.2.*

推荐阅读