显示和播放输入中选择的音频文件 JavaScript

Display and play audio file selected in input JavaScript

我找不到如何播放用户刚刚通过输入 select 编辑过的音频文件。 我有以下输入:

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

我想在用户 select 播放音频文件时显示它,以便他可以播放。应该是这样的:

('#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());
});

我希望你明白我想做什么,我真的不知道如何解释它(也许这就是为什么我在其他主题上找不到任何答案)。

.val() 实际上没有您放入 input 的文件。你需要使用它的 files 属性.

考虑阅读这篇 MDN 文章,该文章将演示如何使用文件:Using files from web applications and this documentation on URL.createObjectURL() 您需要使用它来为您的 <audio> 提供 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>