1

I am creating a web where you can upload mp3 files through file dialog, but I don't know how to tell the web to play that sound the user uploaded (?

  function importData() 
{
     let input = document.createElement('input');
     input.type = 'file';
     input.onchange = e => {
    // you can use this method to get file and perform respective operations
     var file = e.target.files[0];
     console.log(file.name);
   }
}
Sarthak Raval
  • 1,001
  • 1
  • 10
  • 23
lautodev
  • 11
  • 1
  • 2
    Does this answer your question? [play mp3 file loaded by user via file selector](https://stackoverflow.com/questions/20585899/javascript-html5-audio-play-mp3-file-loaded-by-user-via-file-selector-in-andr) Also see [Play Uploaded Audio](https://stackoverflow.com/questions/28619550/javascript-play-uploaded-audio) and [Upload and Play Audio File](https://stackoverflow.com/questions/43710173/upload-and-play-audio-file-js). – showdev Sep 17 '21 at 04:52

1 Answers1

0

Once you have the filename from the user you need to get its content which you can do using a FileReader. Once you have the content this can be put as the src of an HTML5 audio element and played.

Here's a simple example:

function getAudio() {
  const input = document.querySelector('input');
  const audio = document.querySelector('audio');
  input.type = 'file';
  input.onchange = e => {
    var file = e.target.files[0];

    var reader = new FileReader();
    reader.addEventListener('load', function(e) {
      audio.src = e.target.result;
      audio.play();
    });
    reader.readAsDataURL(file);
  }
}
getAudio();
<input>
<audio src=""></audio>
A Haworth
  • 30,908
  • 4
  • 11
  • 14