Play downloaded file in javascript

I am trying to download a file from a user and want to play it using javascript.

The file is loaded correctly, and I can access it by seeing the name, type, etc. using the FileList API.

What I can not do is play the resulting file. I tried to do

 myFile.play(); 

as I always do with a downloaded file, but it does not work.

Any idea?

+4
source share
2 answers

If you want to play media content instead of using FileReader, I suggest you use the createObjectURL method. It is more efficient since it does not create a string containing the contents of the file.

https://developer.mozilla.org/fr/docs/DOM/window.URL.createObjectURL

Just do:

 audio/video.src=window.URL.createObjectURL(myFile); 

Remember to cancel your uri when loading another media file to avoid memory leaks:

 window.URL.revokeObjectURL(audio/video.src); 
+2
source

You also need the FileReader API ( API compatibility ), and your browser needs to support the HTML5 audio tag.

Something like that:

  <body> <input type='file' id='fileInput' /> <audio id='player' /> <script type='javascript'> var fileInput = document.getElementById("fileInput"); var freader = new FileReader(); freader.onload = function(e) { document.getElementById('player').src = e.target.result; document.getElementById('player').play(); } fileInput.onchange = function(e) { var files = e.target.files; freader.readAsDataURL(files[0]); } </script> </body> 

Here you can read here .

My answer is based on migerh solution

+1
source

Source: https://habr.com/ru/post/1481548/


All Articles