Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make AudioBufferSourceNode the audio source of an <audio> tag?

One direction of this exchange is possible - I know you can use the source of an <audio> element as a means of getting audio for use with the Web Audio API via createElementSourceNode(). Is it possible to do the opposite, where an AudioBufferSourceNode is used as the source for an <audio> element?

I'm pretty sure this is impossible, but I've been looking through npm for standard-looking, no-frills recreations of default browser audio element playback controls intended for use with AudioBuffers and I'm not finding anything.

like image 907
Tinstar Avatar asked Aug 01 '19 06:08

Tinstar


Video Answer


1 Answers

You can connect your AudioBufferSourceNode to a MediaStreamDestination node and then feed an HTMLAudioElement srcObject with the .stream property of this node:

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>
like image 136
Kaiido Avatar answered Oct 23 '22 03:10

Kaiido