Created
May 19, 2025 20:07
-
-
Save ali-master/6095064a6194c2d61102443abb132199 to your computer and use it in GitHub Desktop.
Play a Notification Sound in Browser JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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