在现有 HTML5 音频标签中播放 AudioBuffer

Play AudioBuffer in existing HTML5 audio tag

我创建了一个网站,其中包含一个音频标签以及一个用于文件上传的工作拖放区。

<body>
    <audio id="myPlayer" controls>Your browser does not support the audio-tag</audio>
    <div id="dropArea"></div>
</body>

然后将拖动的音频文件转换为 ArrayBuffer,最终转换为 AudioBuffer

let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let arrayBuffer = await readFileAsArrayBuffer(audioFile);

audioContext.decodeAudioData(arrayBuffer, buf => {
    console.log(buf);
});

然后AudioBuffer可以在函数中这样播放:

playSound(buffer) => {
  let source = context.createBufferSource();

  source.buffer = buffer;
  source.connect(context.destination);
  source.start(0);
}

以上所有工作正常,但这不是我所追求的。

我想 AudioBuffer 在我的 HTML 中的音频播放器中播放和控制。这怎么能做到?

要回答我自己的问题,需要从上传的文件中创建 data URL

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

例子

// Helper Function
function readAsDataURL(file) {
  return new Promise((resolve, reject) => {
    if (file instanceof File) {
      reader.onload = () => {
        resolve(reader.result);
      };
      reader.readAsDataURL(file);
    } else {
      reject(new Error("This type of object is not supported"));
    }
  });
}

// Set URL for audio player
(async () => {
  const url = await readAsDataURL(event.dataTransfer.files[0]);
  const audioElement = document.querySelector("#audio-player");

  audioElement.src = url;
})();