在前端,我有一个音频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
您将节省内存和资源,避免编码&;把它解码回来
在使用了Jakub Bláha的评论之后,我通过将python函数更改为:
相关问题 更多 >
编程相关推荐