4

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).

1

2 Answers 2

9

.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>

Sign up to request clarification or add additional context in comments.

Comments

0

Start by setting up the html. Then get the file with an eventlistener and create a object url that is assigned as the audio source:

const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", event => {
    const objUrl = URL.createObjectURL(event.target.files[0]);
    document.getElementById("audioPlayer").src = objUrl;
});
<input type="file" id="fileInput" accept=".mp3">
<audio id="audioPlayer" controls="true"></audio>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.