首页 > 解决方案 > 使 AudioBufferSourceNode 成为

问题描述

这种交换的一个方向是可能的 - 我知道您可以使用<audio>元素的源作为获取音频的一种方式,以便通过createElementSourceNode(). 是否可以做相反的事情,其中​​ anAudioBufferSourceNode用作<audio>元素的来源?

我很确定这是不可能的,但我一直在通过 npm 寻找标准外观、简洁的默认浏览器音频元素播放控件的娱乐,用于使用,AudioBuffers但我没有找到任何东西。

标签: javascripthtml5-audioweb-audio-api

解决方案


您可以将 AudioBufferSourceNode 连接到MediaStreamDestination 节点,然后使用该节点的属性提供HTMLAudioElementsrcObject.stream

start.onclick = e => {

  const audioCtx = new AudioContext();
  fetch("https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3")
  .then(resp => resp.arrayBuffer())
  .then(buf => audioCtx.decodeAudioData(buf))
  .then(audioBuffer => {
    const source = audioCtx.createBufferSource();
    source.buffer = audioBuffer;
    source.playbackRate.value = 0.1;
    source.loop = true;
    source.start(0);
    const streamNode = audioCtx.createMediaStreamDestination();
    source.connect(streamNode);
    const audioElem = new Audio();
    audioElem.controls = true;
    document.body.appendChild(audioElem);
    audioElem.srcObject = streamNode.stream;
  })
  .catch(console.error);
}
<button id="start">start</button>


推荐阅读