How to use ffmpeg in a python function

半腔热情 提交于 2021-02-08 03:34:08

问题


I have tried to use a ffmpeg to extract an audio from a video file and this is my code

import io
import os
import subprocess

def extract_audio(video,output):
    command = "ffmpeg -i '{video}' -ac 1  -f flac -vn '{output}'"
    subprocess.call(command,shell=True)

extract_audio('dm.MOV','dm-new.flac')

And I got no error after compiled. By doing this I should get a new file which is 'dm-new.flac'. But there is no such a flac file created after I compile the script. I think there are something wrong with the syntax or something in the variable 'command' which I have no idea to fix this. My question here is how can I use ffmpeg in a python function base on this code?

By the way, I knew that I could just use ffmpeg without writing a function. But I really need to write in in a function. Thank you


回答1:


Try this:

import io
import os
import subprocess

def extract_audio(video,output):
    command = "ffmpeg -i {video} -ac 1  -f flac -vn {output}".format(video=video, output=output)
    subprocess.call(command,shell=True)

extract_audio('dm.MOV','dm-new.flac')

I think you were trying to reference two variables inside a string but did not tell Python that you should replace 'video' and 'output' with their corresponding variables. .format() allows you to reference the variables that you refer to in a string.

See here for more info.




回答2:


Add one character (f) to solve it (over python 3.6):

import subprocess
def extract_audio(video,output):
    command = f"ffmpeg -i '{video}' -ac 1  -f flac -vn '{output}'"
    subprocess.call(command,shell=True)

extract_audio('dm.MOV','dm-new.flac')



回答3:


I think this is it.

import io
import subprocess
def extract_audio(video,output):
    command = "ffmpeg -i {} -ac 1  -f flac -vn {}".format(video,output)
    subprocess.call(command,shell=True)

extract_audio('dm.MOV','dm-new.flac')



回答4:


I belive this should work:

import io
import os
import subprocess

def extract_audio(video,output):
    command = "ffmpeg -i {} -ac 1  -f flac -vn {}".format(video, output)
    subprocess.call(command,shell=True)

extract_audio('dm.MOV','dm-new.flac')


来源:https://stackoverflow.com/questions/52197883/how-to-use-ffmpeg-in-a-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!