gpt4 book ai didi

python - 如何在ffmpeg中使用字节而不是文件路径?

转载 作者:行者123 更新时间:2023-12-04 23:20:41 24 4
gpt4 key购买 nike

我有一个当前接收字节的函数,将其保存到磁盘上的音频 WEBM 文件,然后将其转换为磁盘上的另一个音频 WAV 文件。
我正在寻找一种方法来进行上述转换,而无需使用 FFMPEG 将 WEBM 文件保存到磁盘。
FFMPEG 可以使用内存中的字节而不是磁盘中文件的路径来处理此类转换吗?
我现在在做什么(Python 3.8.8 64Bit):

# audio_data = bytes received

def save_to_webm(audio_data, username):
mainDir = os.path.dirname(__file__)
tempDir = os.path.join(mainDir, 'temp')
webm_path = os.path.join(tempDir, f'{username}.webm')
with open(webm_path, 'wb') as f:
f.write(audio_data)
return webm_path

# webm_path = input path in FFMPEG

def convert_webm_to_wav(webm_path, username):
mainDir = os.path.dirname(__file__)
tempDir = os.path.join(mainDir, 'temp')
outputPath = os.path.join(tempDir, f'{username}.wav')

if platform == 'win32':
ffmpeg_path = os.path.join(mainDir, 'ffmpeg.exe')
else:
os.chdir("/ffmpeg")
ffmpeg_path = './ffmpeg'

command = [ffmpeg_path, '-i', webm_path, '-acodec', 'pcm_s16le', '-ar', '11025', '-ac', '1', '-y', outputPath]
subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
return outputPath

最佳答案

您可以轻松拥有ffmpeg使用 - 从标准输入读取字节作为文件名;但是您可能希望它与读取它们的进程并行运行,而不是将它们全部读入内存然后开始转换。
但是对于一个快速的原型(prototype),也许可以尝试这样的事情:

def convert_webm_save_to_wav(audio_data, username):
mainDir = os.path.dirname(__file__)
tempDir = os.path.join(mainDir, 'temp')
wav_path = os.path.join(tempDir, f'{username}.wav')

if platform == 'win32':
ffmpeg_path = os.path.join(mainDir, 'ffmpeg.exe')
else:
# Almost certainly should not need to os.chdir here
ffmpeg_path = '/ffmpeg/ffmpeg'

command = [ffmpeg_path, '-i', '-', '-acodec', 'pcm_s16le',
'-ar', '11025', '-ac', '1', '-y', wav_path]
subprocess.run(command, input=audio_data)

return wav_path
在脚本目录中创建临时目录的约定是可疑的;你可能应该使用 Python 的 tempfile 模块,或者让调用用户指定他们想要文件的位置。

关于python - 如何在ffmpeg中使用字节而不是文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66931280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com