繁体   English   中英

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

[英]How to use bytes instead of file path in ffmpeg?

我有一个 function 当前接收字节,将其保存到磁盘上的音频 WEBM 文件,然后将其转换为磁盘上的另一个音频 WAV 文件。

我正在寻找一种在不将 WEBM 文件保存到磁盘的情况下使用 FFMPEG 进行上述转换的方法。

FFMPEG 可以使用 memory 中的字节而不是磁盘中文件的路径来处理此类转换吗?

我现在在做什么(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从标准输入读取字节; 但是您可能希望它与读取它们的过程并行运行,而不是将它们全部读入 memory 然后开始转换。

但是对于一个快速的原型,也许可以尝试这样的事情:

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, stdin=subprocess.PIPE, input=audio_data)

    return wav_path

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM