Lyl*_*att 7 python subprocess ffmpeg pyffmpeg
我正在尝试使用ffmpeg和Python的子进程模块来转换一些音频文件.我从URL中获取音频文件,并希望能够将Python文件对象传递给ffmpeg,而不是先将它们保存到磁盘.如果我能够取回文件流而不是让ffmpeg将输出保存到文件中,那也是非常好的.
作为参考,这就是我现在正在做的事情:
tmp = "/dev/shm"
audio_wav_file = requests.get(audio_url)
## ## ##
## This is what I don't want to have to do ##
wavfile = open(tmp+filename, 'wrb')
wavfile.write(audio_wav_file.content)
wavfile.close()
## ## ##
conversion = subprocess.Popen('ffmpeg -i "'+tmp+filename+'" -y "'+tmp+filename_noext+'.flac" 2>&1', shell = True, stdout = subprocess.PIPE).stdout.read()
Run Code Online (Sandbox Code Playgroud)
有谁知道如何做到这一点?
谢谢!
使用ffmpeg,您可以使用-输入/输出文件名来指示它应该从stdin/write到stdout读取数据.
然后,您可以使用stdin/ stdoutarguments Popen来读取/写入数据.
一个例子:
from subprocess import Popen, PIPE
with open("test.avi", "rb") as infile:
p=Popen(["ffmpeg", "-i", "-", "-f", "matroska", "-vcodec", "mpeg4",
"-acodec", "aac", "-strict", "experimental", "-"],
stdin=infile, stdout=PIPE)
while True:
data = p.stdout.read(1024)
if len(data) == 0:
break
# do something with data...
print(data)
print p.wait() # should have finisted anyway
Run Code Online (Sandbox Code Playgroud)
相反,您为您提供文件stdin也可以使用a PIPE并直接写入进程输入流(p.stdin).或者在你的情况下,你只需使用wavfile ...
请注意,您必须明确指定输出格式和编解码器,因为ffmpeg无法像通常那样从文件扩展名中猜出它们.
它只适用于不需要可搜索输出流的多路复用器,但是flac应该工作......