All files / src/renderer/lib/soundfx soundfx.ts

0% Statements 0/40
0% Branches 0/1
0% Functions 0/8
0% Lines 0/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                                                               
let globalAudioCtx: AudioContext | undefined = undefined;
 
export const playTone = (frequency: number, duration: number) => {
  const audioCtx = getAudioCtx();
  const gainNode = audioCtx.createGain();
  const oscillator = audioCtx.createOscillator();
 
  gainNode.gain.value = 0.2;
 
  oscillator.type = "square";
  oscillator.frequency.setValueAtTime(frequency, audioCtx.currentTime);
 
  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);
  oscillator.start();
 
  setTimeout(() => {
    oscillator.stop();
    gainNode.disconnect();
  }, duration);
 
  return oscillator;
};
 
export const stopTone = (oscillator: OscillatorNode) => {
  oscillator.stop();
};
 
export const decodeAudioData = (buffer: ArrayBuffer) => {
  const audioCtx = getAudioCtx();
  return audioCtx.decodeAudioData(buffer);
};
 
export const playBuffer = (audioBuffer: AudioBuffer) => {
  const audioCtx = getAudioCtx();
  const source = audioCtx.createBufferSource();
  source.buffer = audioBuffer;
  source.connect(audioCtx.destination);
  source.start();
  source.onended = () => {
    source.disconnect();
  };
  return source;
};
 
export const stopBuffer = (bufferSource: AudioBufferSourceNode) => {
  bufferSource.stop();
};
 
const getAudioCtx = () => {
  Iif (!globalAudioCtx) {
    globalAudioCtx = new window.AudioContext();
  }
  return globalAudioCtx;
};