Display and play audio file selected in input JavaScript

我怕爱的太早我们不能终老 提交于 2019-12-24 03:14:47

问题


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:


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


来源:https://stackoverflow.com/questions/54932711/display-and-play-audio-file-selected-in-input-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!