Skip to content

how to convert blob to wav file in javascript and connect python flask

I want to create web app using STT model by python flask. when user record the voice and send it server, trans it to text on web.

there is my javascript part:


  <div style="text-align: center;">
      <button type="button" id="record">record</button>
      <button type="button" id="stopRecord" disabled>stop</button>
      <input type="button" id="sendRecord" value="trans to text">
      <audio id=recordedAudio></audio>
<script src=""></script>
    let recordBlob;
                          .then(stream => {handlerFunction(stream)})
    function handlerFunction(stream) {
      rec = new MediaRecorder(stream);
      rec.ondataavailable = e => {
        if (rec.state == "inactive") {
          recordBlob = new Blob(audioChunks, {type:'audio/wav; codecs=MS_PCM'});
          recordedAudio.src = URL.createObjectURL(blob);
    record.onclick = e => {
        record.disabled = true; = "blue"
        audioChunks = [];
    stopRecord.onclick = e => {
      record.disabled = false;
      stop.disabled=true; = "red"

    sendRecord.onclick = e => {
      let formData = new FormData();
      formData.append('data', recordBlob);
      console.log('blob', recordBlob);
        type: 'POST',
        url: '/result',
        data: formData,
        contentType: false,
        processData: false,
        success: function(result) {
          console.log('success', result);
          $("#chatbox").append(`<p class ="userText"><audio style="background-color:white;" controls> <source src="${Url}" type="audio/wav"></audio></p>`);
          $("#chatbox").append(`<p class ="botText"><span>${result.emotion}</span></p>`);
        error: function(result) {
          alert('sorry an error occured');

and there is flask part:

from flask import Flask, render_template, request
import requests, json
import soundfile
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

def index():
    return render_template('index.html')

@app.route('/result', methods=['POST'])
def result():
    url = ""
    key = 'REST API KEY'
    headers = {
        "Content-Type": "application/octet-stream",
        "Authorization": "KakaoAK " + key,

    blobData = request.files['data']
    filename = secure_filename(blobData.filename)
    filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)'blob data : ', blobData)
    data, samplerate =

    soundfile.write('new.wav', data, samplerate, subtype='PCM_16')

    with open("new.wav", 'rb') as fp:
        audio =

    res =, headers=headers, data=audio)
    return res.text

if __name__=='__main__':
    app.debug=True'', port=5001)

it comes out error

[2022-02-25 19:27:51,895] ERROR in app: Exception on /result [POST]
Traceback (most recent call last):
  File "", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:UsersLJHDocuments코드스테이츠개인프로젝트", line 31, in result
    data, samplerate =
  File "", line 372, in read
    with SoundFile(file, 'r', samplerate, channels,
  File "", line 740, in __init__
    self._file = self._open(file, mode_int, closefd)
  File "", line 1264, in _open
  File "", line 1455, in _error_check
    raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening <FileStorage: 'blob' ('audio/wav; codecs=ms_pcm')>: File contains data in an unknown format. - - [25/Feb/2022 19:27:51] "POST /result HTTP/1.1" 500 -

I don’t know why blob didn’t convert to wav…how can I fix it? probably there are many no necessary parts on my javascript code.. I don’t know about javascript. I’m sorry for that.



You write the data in a file, the position within the file moves to the end of it. If you then re-read the file using soundfile, you must first jump back to the beginning of the file.

import io

@app.route('/result', methods=['POST'])
def result():
    if 'data' in request.files:
        file = request.files['data']
        # Write the data to a file.
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
        # Jump back to the beginning of the file.
        # Read the audio data again.
        data, samplerate =
        with io.BytesIO() as fio:
            data = fio.getvalue()
        # ...

   return '', 400