简体   繁体   English

如何在 python 中运行 ffmpeg 命令; 代码?

[英]How to run ffmpeg command in python; vscode?

i'd like to run this command我想运行这个命令

for /R %f IN (/*.mp4) DO ffmpeg -i "%f" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 %~nf.wav

inside this script, like this:在这个脚本里面,像这样:

import os
from datetime import date

today = date.today()
today = today.strftime('%m-%d-%Y')
dir_name = f"C:/Users/lucan/Automatically/{today}/"

def extract(user):
  test = os.listdir(dir_name)
  command = "for /R %f IN (/*.mp4) DO ffmpeg -i "%f" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 %~nf.wav"
  os.system(command)
  for item in test:
    if item.endswith(".wav"):
      os.remove(os.path.join(dir_name, item))


extract("businessbarista")

when i do so this is the error message I get:当我这样做时,这是我收到的错误消息:

command = "for /R %f IN (/*.mp4) DO ffmpeg -i "%f" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 %~nf.wav" TypeError: must be real number, not str command = "for /R %f IN (/*.mp4) DO ffmpeg -i "%f" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 %~nf.wav" TypeError: must be real number,不是 str

the command runs fine in command prompt, but not in powershell.该命令在命令提示符下运行良好,但在 powershell 中运行良好。 can you help me figure out what went wrong?你能帮我找出问题所在吗?

Why mix Python & batch scripts?为什么要混合 Python 和批处理脚本?

If I understood the batch script for loop syntax, the following should be equivalent in Python:如果我理解循环语法的批处理脚本,那么 Python 中的以下内容应该是等效的:

from glob import glob
import subprocess as sp
from os import path

# FFmpeg command (missing input & output)
cmd = ['ffmpeg','-i',None,'-f','wav','-bitexact','-acodec','pcm_s16le','-ar','22050','-ac','1']

# likely equivalent to 'for /R %f IN (/*.mp4) DO '
for input in glob("**/*.mp4",recursive=True): 
    cmd[3] = input
    output = path.splitext(input)[0] + '.wav'
    sp.run([*cmd,output])

This snippet scans the current folder and all its subfolders and lists all mp4 files in them and return the relative paths.此片段扫描当前文件夹及其所有子文件夹并列出其中的所有 mp4 文件并返回相对路径。 eg, mp4\video.mp4 .例如, mp4\video.mp4 Then os.path.splitext() removes the file extension to form the output file path.然后os.path.splitext()去掉文件扩展名,形成 output 文件路径。

You have " " inside " " and this makes problem.你有" "里面" " ,这会产生问题。

It treats it as two strings "first" %f "second" .它将其视为两个字符串"first" %f "second"

You have to replace one pair of " " with ' ' - like ' " " ' or " ' ' " .您必须将一对" "替换为' ' - 例如' " " '" ' ' "

Or you have to use \ like " \" \" "或者你必须使用\ like " \" \" "

command = 'for /R %f IN (/*.mp4) DO ffmpeg -i "%f" -f wav -bitexact -acodec pcm_s16le -ar 22050 -ac 1 %~nf.wav'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM