Upload audio recorded in browser using html5

2019-04-10 05:13发布

问题:

I'm a newbie to HTML, Javascript and company, so please forgive me for asking a perhaps obvious question.

I'd like to build a webapp where users can upload audio plus some information about themselves. I have a form that looks mostly like this:

<form method="post" action="/add_recording" enctype="multipart/form-data">
  <label>Name: </label>
  <input type="text" name="user_name" maxlength="20" size="20" value="Joe">
  <br>
  <label>Audio File: </label>
  <input type="file" name="user_audio"/>
  <br>
  <input value="Upload" type="submit">
</form>

This works, but it's not very user-friendly: people have to figure out how to create their own audio files, and even if they know how, it's annoying. I'd like to allow users to record in-browser. I found https://github.com/mattdiamond/Recorderjs and http://webaudiodemos.appspot.com/AudioRecorder/index.html, which look very cool (ignoring for the moment the fact that they only work on very recent builds of chrome, as far as I can tell).

My question is: how can I modify the recorderjs code so that the recorded blob is automatically uploaded in my form, without the user having to download the file and manually browse to it by clicking on the type="file" input?

My web development skills are extremely limited, so I'd be very thankful for any help. My first guess was to automatically download the audio blob to a filename of my choosing, and modify the type="file" input in the form to point there, but apparently this is impossible (from what I see in e.g. How to set a value to a file input in HTML?).

Thank you,

Adrian

Edit: There's a similar question here: RecorderJS uploading recorded blob via AJAX. One solution to my problem would be to learn AJAX and follow the answer in that question. Still, I'd be interested to know whether there's any way to upload the recorderjs audio using an old-fashioned file input (or an html form more generally).

回答1:

Here's how I ended up doing it, in case this helps anyone else:

function uploadForm() {
    var form = new FormData(document.getElementById("my_form"));
    form.append("user_audio_blob", audioBlob);
    var request = new XMLHttpRequest();
    var async = true;
    request.open("POST", "/my_form_handler", async);
    if (async) {
        request.onreadystatechange = function() {
            if(request.readyState == 4 && request.status == 200) {
                var response = null;
                try {
                    response = JSON.parse(request.responseText);
                } catch (e) {
                    response = request.responseText;
                }
                uploadFormCallback(response);
            }
        }
    }
    request.send(form);
}

That and a slight modification to the recorderjs code to set audioBlob. When I originally posted the question I did not know about FormData and form.append.