PROWAREtech
JavaScript: Play a Pop Sound in a Web Browser
How to play a pop sound in an Internet browser.
It is easy to create a "POP" sound for purposes of bringing attention to the user. NOTE: This does not work on Safari for iOS/PadOS.
var unlockAudio = function (ctx) {
if (ctx.state != "suspended")
return;
var b = document.body;
var events = ["touchstart", "touchend", "mousedown", "keydown"];
events.forEach(function (e) {b.addEventListener(e, unlock, false);} );
function unlock() {
ctx.resume().then(clean);
}
function clean() {
events.forEach(function (e) {b.removeEventListener(e, unlock);} );
}
};
// Create a global audio context (outside of function)
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
unlockAudio(audioContext); // NOTE: IF NOT SAFARI THEN DO NOT CALL THIS FUNCTION!
var playPopSound = function () {
// Create an oscillator node (for the pop sound)
var oscillator = audioContext.createOscillator();
oscillator.type = "sine"; // A simple sine wave works well for a pop sound
oscillator.frequency.setValueAtTime(400, audioContext.currentTime); // Start at 400 Hz
oscillator.frequency.exponentialRampToValueAtTime(200, audioContext.currentTime + 0.1); // Lower frequency quickly
// Create a gain node to control volume
var gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(1, audioContext.currentTime); // Start at full volume
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.1); // Fade out quickly
// Connect the oscillator to the gain node, then to the audio context's destination
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
// Start the oscillator
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.1); // Stop after 0.1 seconds for a short pop sound
};
Comment