gpt4 book ai didi

javascript - 在 flask 后端保存音频

转载 作者:行者123 更新时间:2023-12-03 00:07:40 25 4
gpt4 key购买 nike

在前端,我有一个音频Blob,尝试将其发送到Flask后端,在该后端需要对音频进行一些处理。
目前,我将音频作为base64字符串发布到Flask。然后在Flask中,我将字符串编码为base64,然后尝试将其保存到本地文件系统中。它被保存为webm文件,但是,当我尝试播放音频时,即使base64字符串已保存到文件中,也为0秒。
您知道为什么音频可能无法正常播放吗?如何使音频在后端正常播放?
前端:

mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { 'type' : 'audio/webm'});
const reader = new FileReader();
reader.readAsDataURL(audioBlob);
reader.onload = () => {
const base64AudioMessage = reader.result.split(',')[1];
console.log(reader.result)
fetch("http://localhost:5000/api/audio", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: base64AudioMessage })
}).then(res =>
{console.log(res)});
}
})
后端:
@app.route('/api/audio', methods=['POST'])
def audio():
content = request.get_json(silent=True)
print(type(content["message"])) #This is type string
ans = base64.b64encode(bytes(content["message"], 'utf-8'))
print(type(ans)) #This is type bytes
with open("audioToSave.webm", "wb") as fh:
fh.write(base64.b64decode(ans))
theAnswer = 'no'
return theAnswer

最佳答案

我不认为您应该将音频文件上传为base64,如果仅发送不带任何额外元数据,字段或json的数据,则将其上传为原始数据会大33%,否则请使用FormData

mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { 'type' : 'audio/webm'})
fetch(url, { method: 'POST', body: audioBlob })
})

// or

mediaRecorder.addEventListener("stop", () => {
const fd = new FormData()
const audioBlob = new Blob(audioChunks, { 'type' : 'audio/webm'})
fd.set('file', audioBlob, 'audioToSave.webm')
fetch(url, { method: 'POST', body: fd })
})
您将节省内存和资源,避免对其进行编码和解码

关于javascript - 在 flask 后端保存音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62487798/

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