How the onchange event works when uploading a file

0

I'm trying to implement a music player using javascript, which works by uploading an audio file (.mp3), in the script when uploading the file, which occurs with the 'onload' event the function created has the variable 'files' and then play the file. How does the file get played if it does not seem to reference the variable that receives the 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();
    }

};   

Thank you in advance.

    
asked by anonymous 07.01.2018 / 20:49

1 answer

2

I have modified the id of your audio element and the 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 in arquivo and file element, not the imported file.

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

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

When you give play to variable musica , you are saying to reproduce the element audio , which contains the new src of file imported.

More information about this change in src : link

More information about the input file : link

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

I hope it helps!

    
08.01.2018 / 16:23