简体   繁体   English

如何使用python将base64解码为wav格式?

[英]How to decode base64 to wav format using python?

I have audio recordings saved on a server as base64, webm format and want to decode them with python into a wav file.我将录音保存在服务器上,格式为 base64,webm 格式,我想用 python 将它们解码为 wav 文件。 I tried both suggested ways from a simliar question found here: How to decode base64 String directly to binary audio format .我尝试了从此处发现的类似问题中提出的两种建议方法: How to decode base64 String directly to binary audio format But I'm facing different problems with both suggestions:但是我对这两个建议都面临不同的问题:

The version using file.write resulted in a wav file that I could play with the VLC player and which included the expected content.使用 file.write 的版本生成了一个 wav 文件,我可以用 VLC 播放器播放它,其中包含预期的内容。 But I got an error message when I tried to read it with matlab or python saying "unknown format" or "missing riff".但是,当我尝试使用 matlab 或 python 读取它时,我收到一条错误消息,提示“未知格式”或“缺少重复段”。

fin = open(dirName + file, "r") 
b64_str = fin.read()
fin.close()
# decode base64 string to original binary sound object
decodedData = base64.b64decode(b64_str)

webmfile = (outdir + file.split('.')[0] + ".webm")
wavfile = (outdir + file.split('.')[0] + ".wav")

with open(webmfile , 'wb') as wm:
    wm.write(decodedData)
with open(webmfile, 'rb') as wm:
    webmdata = pcm.read()
with open(wavfile, 'wb') as file:
        file.write(webmdata)

The version using writeframes with setting the parameters result in a file I could read with matlab or python but this one does not contain the expected content and is way shorter than expected.使用 writeframes 并设置参数的版本生成一个我可以用 matlab 或 python 读取的文件,但这个文件不包含预期的内容,而且比预期的要短。

with wave.open(wavfile, 'wb') as wav:
        wav.setparams((1, 2, 48000, 0, 'NONE', 'NONE'))
        wav.writeframes(webmdata)

Any ideas on how to solve this problem?关于如何解决这个问题的任何想法? The file itself is fine.文件本身没问题。 Converting it with an online converter worked.使用在线转换器转换它有效。

In case someone has the same problem at some point, here is the solution which worked for me: The following code creates a webm file from the base64 str:如果有人在某个时候遇到同样的问题,这里是对我有用的解决方案:以下代码从 base64 str 创建一个 webm 文件:

import base64

decodedData = base64.b64decode(b64_str)
webmfile = (outdir + file.split('.')[0] + ".webm")
with open(webmfile, 'wb') as file:
       file.write(decodedData)

And for the conversion I used ffmpy:对于我使用 ffmpy 的转换:

from ffmpy import FFmpeg

ff = FFmpeg(
        executable = 'C:/Program Files/ffmpeg-2020/bin/ffmpeg.exe',
        inputs={file:None},
        outputs = {outfile:'-c:a pcm_f32le'})
ff.cmd
ff.run()

After those two steps, I was able to read the resulting wav file with matlab or any other program.在这两个步骤之后,我能够使用 matlab 或任何其他程序读取生成的 wav 文件。

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

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