web-audio-api icon indicating copy to clipboard operation
web-audio-api copied to clipboard

How to clear AudioContext?

Open 0plus1 opened this issue 9 months ago • 0 comments

Hi, thanks for this package, I am streaming to Speaker, everything works, but if I run the code below, it will keep the CLI running, what is the correct way to close the AudioContext? audioCtx._kill() does close it but creates some weird scenarios.

Thanks for any help.

import { AudioContext } from 'web-audio-api';
import Speaker from 'speaker';

// Initialise audio context setting speaker as the streaming device
let audioCtx = new AudioContext;
audioCtx.outStream = new Speaker({
  channels: audioCtx.format.numberOfChannels,
  bitDepth: audioCtx.format.bitDepth,
  sampleRate: audioCtx.sampleRate
});

async function playBuffer(buffer) {
  return new Promise((resolve, reject) => {
    const source = audioCtx.createBufferSource();
    source.buffer = buffer;
    source.connect(audioCtx.destination);
    source.loop = false;
    source.start(0);
    source.onended = () => {
      resolve();
    };
    source.onerror = (err) => {
      reject(err);
    };
  });
}

export async function streamAudio(arrayBuffer) {
  return new Promise(async (resolve, reject) => {
    try {
      // Decode it
      audioCtx.decodeAudioData(
        arrayBuffer,
        (b) => playBuffer(b).then(() => {
          // Not sure what's the correct way to close the audio context
          // This line creates race condition as the audio might've not finished playing
          // audioCtx._kill();
          resolve();
        }),
        (err) => reject(err)
      );
    } catch (err) {
      reject(`Unable to fetch the audio file. Error: ${err.message}`);
    }
  });
}

0plus1 avatar Nov 27 '23 10:11 0plus1