问题
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