5

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

<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 中的音频播放器中播放和控制。如何才能做到这一点?

4

1 回答 1

1

要回答我自己的问题,需要从上传的文件创建一个数据 URL 。

readAsDataURL 方法用于读取指定 Blob 或 File 的内容。当读操作完成后,readyState 变为 DONE,并触发 loadend。当时,result 属性包含数据作为 data: URL 将文件数据表示为 base64 编码字符串。

例子

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

于 2021-03-29T07:58:12.700 回答