在flask后端保存音频

2024-09-27 21:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在前端,我有一个音频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

Tags: 文件字符串flaskmessagenewtypecontent音频
3条回答

仅供参考。我正在开发这个代码,还不完善,我正在丢失一些音频帖子

前端

function blogUpload(blob){
        var xhr=new XMLHttpRequest();
        xhr.onload=function(e) {
            if(this.readyState === 4) {
                console.log("Server returned: ",e.target.responseText);
            }
        };

        var fd=new FormData();
        fd.append("audio_data",blob, 'temp.wav');
        xhr.open("POST","uploader",true);  
        xhr.onprogress = function (e) {
        if (e.lengthComputable) {
            console.log(e.loaded+  " / " + e.total)
            }
        }

        xhr.onloadstart = function (e) {
            console.log("start")
        }

        xhr.onloadend = function (e) {
            console.log("end")
        }

        xhr.send(fd);
    }

后端

    @app.route('/uploader', methods = ['GET', 'POST'])
        def upload_file():
        if request.method == 'POST':
            f = request.files['audio_data']
            f.save('audio.wav')
            f.flush()
            f.close()
        return 'file uploaded successfully'

我认为您不应该将音频文件作为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 })
})

您将节省内存和资源,避免编码&;把它解码回来

在使用了Jakub Bláha的评论之后,我通过将python函数更改为:

@app.route('/api/audio', methods=['POST'])
def audio():
    content = request.get_json(silent=True)
    print(type(content["message"])) #This is type string
    ans = base64.b64decode(bytes(content["message"], 'utf-8'))
    print(type(ans)) #This is type bytes
    with open("audioToSave.webm", "wb") as fh:
        fh.write(ans)
    theAnswer = 'no'
    return theAnswer

相关问题 更多 >

    热门问题