Search code examples
javascripthtml5-audio

Display and play audio file selected in input JavaScript


I can't find how to play an audio file that the user has just selected with an input. I have the following input :

<input type='file' id="audio-input" class="audio-input" name="audio" accept=".mp3, .wav"/>

I would like display the audio file when the user select it so he can play it. It would be something like that :

('#audio-input-0').change( function () {

    let audio =
        "<audio controls>" +
        "     <source id='audioFile' type='audio/mpeg'>" +
        "     Your browser does not support the audio element." +
        "</audio>";

    $('body').append(audio);

    $('#audioFile').attr('src', $(this).val());
});

I hope you understand what I'm trying to do, I don't really know how to explain it (maybe that's why I don't find any answers on other topics).


Solution

  • .val() doesn't actually have the file you put into the input. You need to use its files property.

    Consider reading this MDN article that will demonstrate using files: Using files from web applications and this documentation on URL.createObjectURL() which you need to use in order to provide your <audio> with a src.

    function changeHandler({
      target
    }) {
      // Make sure we have files to use
      if (!target.files.length) return;
    
      // Create a blob that we can use as an src for our audio element
      const urlObj = URL.createObjectURL(target.files[0]);
    
      // Create an audio element
      const audio = document.createElement("audio");
    
      // Clean up the URL Object after we are done with it
      audio.addEventListener("load", () => {
        URL.revokeObjectURL(urlObj);
      });
    
      // Append the audio element
      document.body.appendChild(audio);
    
      // Allow us to control the audio
      audio.controls = "true";
    
      // Set the src and start loading the audio from the file
      audio.src = urlObj;
    }
    
    document
      .getElementById("audio-upload")
      .addEventListener("change", changeHandler);
    <div><label for="audio-upload">Upload an audio file:</label></div>
    <div><input id="audio-upload" type="file" /></div>