1

Let´s say I have an audio file recorded by a user in the browser. I would like to

  1. get the file
  2. load the file into input of a form

Some older posts talk about how this is not possible due to security issues, but now it is a possibility according to this answer: how to set file input after file drop

form:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

<div class='col-sm-6' style="padding-left:0px;" >
    <form action="/main/" method="post" id="my_form" enctype="multipart/form-data">
        {% csrf_token %}

        <div> <input type="file" name="audio" id="id_audio" /> </div>


        <button type="submit" disabled style="display: none" aria-hidden="true"></button>
        <input class="btn btn-success" type="submit" name="submit" value="Gem" />
    </form>
</div>

audio file:

<ol id="recordingsList">
    <li id="myfile">
        <audio controls="" src="blob:http://127.0.0.1:8000/99888"></audio>
        myaudiofile.wav 
    </li>
</ol>

function to create the audio control and link to download the file, I want to append the file to id_audio input in the form:

<script>

    function createDownloadLink(blob) {

        var url = URL.createObjectURL(blob);
        var au = document.createElement('audio');
        var li = document.createElement('li');
        var link = document.createElement('a');

        $(li).attr('id', 'recordedaudio-id');
        $(link).attr('id', 'savetodisk');

        //name of .wav file to use during upload and download (without extendion)
        var filename = new Date().toISOString();

        //add controls to the <audio> element    
        au.controls = true;
        au.src = url;

        //save to disk link
        link.href = url;
        link.download = filename+".wav"; //download forces the browser to donwload the file using the  filename
        link.innerHTML = "Save to disk";

        //add the new audio element to li
        li.appendChild(au);


        //add the filename to the li
        li.appendChild(document.createTextNode(filename+".wav "))

        //add the save to disk link to li
        li.appendChild(link);

        //upload link
        var upload = document.createElement('a');
        upload.href="#";
        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","upload.php",true);
            xhr.send(fd);
        })
        li.appendChild(document.createTextNode (" "))//add a space in between
        li.appendChild(upload)//add the upload link to li


        recordingsList.appendChild(li);

        var fileElement = $('#myfile');
        var audioFormElement = $('#id_audio');

        // get the audio file from fileElement
        // set audio file in audioFormElement

    }


</script>
DevB2F
  • 4,674
  • 4
  • 36
  • 60
  • Did you study this yet? https://developers.google.com/web/fundamentals/media/recording-audio/ Looks like you can upload the stream directly. – wannadream Nov 23 '18 at 03:59
  • What part are you referring to? As I understand this code the listener waits for a file to be chosen by a user and then adds that file to the audio control so the user can listen to the file, but I don't see how the input is being set programmatically – DevB2F Nov 23 '18 at 04:03
  • navigator.mediaDevices.getUserMedia({ audio: true, video: false }) .then(**handleSuccess**); You can implement your own handler there. That is using `MediaRecorder` API. – wannadream Nov 23 '18 at 04:08
  • ok I understand, what should I put inside the handler? – DevB2F Nov 23 '18 at 04:14

1 Answers1

-1

Based on the MediaRecorder API (https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder), possible solution:

Store it locally:

<script>
  var handleSuccess = function(stream) {        
    var link = document.createElement('a');
    link.textContent = 'Download';
    link.target = '_blank';
    link.setAttribute("download", 'audio_1.ogg');

    if (window.URL) {
      link.href = window.URL.createObjectURL(stream);
    } else {
      link.href = stream;
    }

    // Append <a> to where you want to.
  };
</script>

Upload it using XMLHttpRequest:

var chunks = [];
var handleSuccess = function(stream) {
  var mediaRecorder = new MediaRecorder(stream);
  mediaRecorder.ondataavailable = function(e) {
    chunks.push(e.data);
  };
  mediaRecorder.requestData();
  var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });

  var xhr = new XMLHttpRequest();
  xhr.onload = function(e) {
    if(this.readyState === 4) {
      console.log("Server returned: ", e.target.responseText);
    }
  };
  var formData = new FormData();
  formData.append("audio_data", blob, 'audio_1.ogg');
  xhr.open("POST", "upload.php", true);
  xhr.send(formData);
}
wannadream
  • 1,669
  • 1
  • 12
  • 14
  • 1
    This isn't what the question is asking. They want to set the blob as the file input in the existing on-page form. – Brad Nov 23 '18 at 05:37