Let´s say I have an audio file recorded by a user in the browser. I would like to
- get the file
- 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>