Home > Mobile >  How to run ffmpeg command in python; vscode?
How to run ffmpeg command in python; vscode?

Time:09-20

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

the command runs fine in command prompt, but not in powershell. can you help me figure out what went wrong?

CodePudding user response:

You have " " inside " " and this makes problem.

It treats it as two strings "first" %f "second".

You have to replace one pair of " " with ' ' - like ' " " ' or " ' ' ".

Or you have to use \ like " \" \" "

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

CodePudding user response:

Why mix Python & batch scripts?

If I understood the batch script for loop syntax, the following should be equivalent in 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. e.g., mp4\video.mp4. Then os.path.splitext() removes the file extension to form the output file path.

  • Related