How the onchange event works when uploading a file

Asked

Viewed 295 times

0

I’m trying to implement a music player using javascript, which works by uploading an audio file (.mp3), in the script when the file is uploaded, which occurs with the 'onload' event the function created has the variable 'files' and then play the file. How the file is played if it apparently does not reference the variable that receives the file 'file'?

HTML

<div id="content">
    <input type="file" id="thefile" accept="audio/*" /> 
    <audio id="audio" controls="controls"></audio> 
</div>

Javascript

window.onload = function() {

    var file = document.getElementById("thefile");
    var audio = document.getElementById("audio");


    file.onchange = function() {
        var files = this.files;
        audio.src = URL.createObjectURL(files[0]);
        audio.load();
        audio.play();
    }

};   

Grateful from now on.

1 answer

2


I modified the id of your audio element and file so as not to confuse your variable with the element itself.

<div id="content">
  <input type="file" id="arquivo" accept="audio/*" /> 
  <audio id="musica" controls="controls"></audio> 
</div>

var musica = document.getElementById("musica"); 
var arquivo = document.getElementById("arquivo");

You store in the variable musica the audio element([Object Htmlaudioelement]) of your document, and arquivo and element file, and not the imported file.

What happens is that every time there’s a change in the file, you store a list of files in var files using the .files, and you pass the first element files[0] to the src of the audio element.

var files = this.files;
musica.src = URL.createObjectURL(files[0]);

When you give the play in the variable musica, you’re saying to reproduce the element audio, containing the new src of file imported.

More information about this change in the src: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURl

More information about the input file: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file

You can observe the change of src of the audio element inspected the page(crtl + Shif + i in Chrome) and importing a new file.

I hope it helps!

  • thanks for the explanation, helped mto, but my doubt persists in the part of the role played by the variable files.

  • I edited the answer with the explanation of files

Browser other questions tagged

You are not signed in. Login or sign up in order to post.