skip to Main Content

Considering the requirement of this function signature:

function initPlayer(player: HTMLAudioElement, buffer: AudioBuffer): void;

I’m looking for a way to control the AudioBuffer playback using the provided HTMLAudioElement.

I see plenty of examples using the start() method of a AudioBufferSourceNode, such as

const context = new AudioContext();
const destination = context.createMediaStreamDestination();
const source = context.createBufferSource();
source.buffer = buffer;  // some AudioBuffer instance
source.connect(destination);
source.start(0);

However this only plays the audio, it does not bind it to the player’s controls; play, pause, stop, seek, etc. have no effect.

There are also other solutions, using a Blob, or an ArrayBuffer from some downloaded mp3 file, for example. However the provided AudioBuffer is the only value I can work with, here.

I have looked at creating a audio/wav (or audio/mp3) Blob, but I can’t wrap my head around the idea that AudioBuffer can’t be directly played from a HTMLAudioElement.

Why is that, and what’s the proper solution to control the playback using the browser media player?

2

Answers


  1. HTMLAudioElement and AudioBuffer are two separate things which do not interact, for each case the correct one should be chosen, both of them can server the same purpose but the choice should be made according to the circumstances.

    An HTMLAudioElement object loads a file and has its own controls (play, stop etc..).

    An AudioBuffer object will represent a usually short audio clip saved in memory, created by loading a file as well, this one is played by passing it into AudioBufferSourceNode, which is "parallel" to the controls you have in an HTMLAudioElement.

    I advise reading the docs for clarity:

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

    https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer

    https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode

    Login or Signup to reply.
  2. Convert the PCM AudioBuffer channels to an interleaved WAV ArrayBuffer and play that WAV as a Blob in the HTMLAudioElement

    const toArrayBuffer = audioBuffer => {...} // implement your conversion
    
    const wav = toArrayBuffer(audioBuffer)
    const wavBlob = new Blob([wav])
    
    const audio = new Audio() as HTMLAudioElement
    audio.src = URL.createObjectURL(wavBlob)
    audio.play()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search