Skip to content

Playing a sound with the Web Audio API

A React hook to play a sound when a timer ends

You can try it in my workout page

Untitled-1
export function useTimerEndSound() {
  let audioContext: AudioContext | null = null;
  let oscillator: OscillatorNode | null = null;
 
  const playTimerEndSound = () => {
    if (!audioContext) {
      audioContext = new AudioContext();
 
      // Check if the AudioContext is suspended
      if (audioContext.state === 'suspended') {
        // Attempt to resume the AudioContext
        audioContext.resume().catch((error) => {
          console.error('Error resuming AudioContext:', error);
        });
      }
 
      oscillator = audioContext.createOscillator();
      oscillator.type = 'sine';
      oscillator.frequency.value = 440; // Hz
      oscillator.connect(audioContext.destination);
      oscillator.start();
    }
 
    if (oscillator) {
      oscillator.stop(audioContext.currentTime + 0.2); // Play for 200ms
    }
  };
 
  return {playTimerEndSound};
}