Audio recording with Recorder.js and Flask - post data using JavaScript

Viewed 552

Update:

I am using recorder.js to record audio from users and I am able to upload the audio file to my Google Cloud Storage bucket. Submitting the form sends the user to the POST route of my Flask app when I test the app locally. However, it hits the GET route when I run the app on Google AppEngine (flex environment).

I think it has to do with the app.js script using XMLHttpRequest and I tried to change app.js to a form post as described here. However, I am new to JavaScript and can't get this to work.

Here is my form:

<html>
    <head>
        <title>Recording Form</title>
    </head>
    <body>
        <div id="controls">
            <button id="recordButton">Record</button>
            <button id="pauseButton" disabled>Pause</button>
            <button id="stopButton" disabled>Stop</button>
        </div>
        <ol id="recordingsList"></ol>
        <script type="text/javascript" src="/static/js/recorder.js"></script>
        <script type="text/javascript" src="/static/js/app.js"></script>
    </body>
</html>

Here is the part of the JavaScript I am trying to change to use a regular form post rather than XMLHttpRequest :

var upload = document.createElement('a');
upload.href="/record";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
          
    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, filename);
    xhr.open("POST","/record",true);
    xhr.send(fd);
})
li.appendChild(document.createTextNode (" "))//add a space in between
li.appendChild(upload)//add the upload link to li

//add the li element to the ol
recordingsList.appendChild(li);
}

Here is my flask app:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request
    
app = Flask(__name__)

@app.route('/record', methods=['POST'])
def record_post():
    audio_data = request.files['audio_data'].read()
    return 'done with POST'

@app.route('/record', methods=['GET'])
def record():
    return 'done with GET'
    
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)

Thank you for your help.

1 Answers

I found out the issue is that the recorded audio file is not uploaded yet when the speech to text function tries to transcribe it. I am going to set up a pub sub topic/ subscription to wait for the upload to be completed now.

Related