Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created May 19, 2025 20:07
Show Gist options
  • Save ali-master/6095064a6194c2d61102443abb132199 to your computer and use it in GitHub Desktop.
Save ali-master/6095064a6194c2d61102443abb132199 to your computer and use it in GitHub Desktop.
Play a Notification Sound in Browser JS
export const playNotificationSound = (audioContext: AudioContext) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
const options = {
type: 'sine' as OscillatorType,
freq: [
392,
// 523.25,
600,
// 659.25
],
duration: 0.3,
gain: 0.12,
};
const frequencies = options.freq;
const timePerNote = options.duration / frequencies.length;
frequencies.forEach((freq, i) => {
oscillator.frequency.setValueAtTime(
freq,
audioContext.currentTime + i * timePerNote,
);
});
oscillator.type = options.type;
gainNode.gain.setValueAtTime(options.gain, audioContext.currentTime);
gainNode.gain.setTargetAtTime(
0,
audioContext.currentTime + options.duration * 0.7,
0.05,
);
oscillator.start();
oscillator.stop(audioContext.currentTime + options.duration);
};
// Usage
const audioContext = new AudioContext();
playNotificationSound(audioContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment