Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to clear AudioContext? #94

Open
0plus1 opened this issue Nov 27, 2023 · 0 comments
Open

How to clear AudioContext? #94

0plus1 opened this issue Nov 27, 2023 · 0 comments

Comments

@0plus1
Copy link

0plus1 commented Nov 27, 2023

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}`);
    }
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant