Skip to content

Instantly share code, notes, and snippets.

@tr00st
Created April 22, 2021 09:59
Show Gist options
  • Save tr00st/845a8d4e72e94c0eb11f55fdc32b6446 to your computer and use it in GitHub Desktop.
Save tr00st/845a8d4e72e94c0eb11f55fdc32b6446 to your computer and use it in GitHub Desktop.
Silent sound generator hack for Safari audio permissions
// James Cheese 2021 - based on example at https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode
// Build an audio context of whatever type's available
let SupportedAudioContext = null;
if (window.AudioContext !== undefined) {
SupportedAudioContext = window.AudioContext;
} else if (window.webkitAudioContext !== undefined) {
SupportedAudioContext = window.webkitAudioContext;
}
const silentAudioContext = new SupportedAudioContext();
// Create a buffer and ensure it's filled with zeroes (ie: silent)
const buffer = silentAudioContext.createBuffer(2, silentAudioContext.sampleRate * 3, silentAudioContext.sampleRate);
for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
const currentChannelBuffer = buffer.getChannelData(channel);
for (var i = 0; i < buffer.length; i++) {
currentChannelBuffer[i] = 0;
}
}
// Hook the buffer up as a source for the audio context, and start streaming
const source = silentAudioContext.createBufferSource();
source.buffer = buffer;
source.loop = true;
source.connect(silentAudioContext.destination);
source.start();
// Might not be necessary for you - but poll to see if the audio context has started yet, then handle that state change
if (silentAudioContext.state !== "running") {
// Poll to see if the audio context boots itself back up, mark as unmuted if that happens
const interval = setInterval(() => {
if (silentAudioContext.state === "suspended") {
silentAudioContext.resume();
}
if (silentAudioContext.state === "running") {
// We're unmuted - handle that however you need to
clearInterval(interval); // But make sure to stop polling...
}
}, 500);
} else {
// We're unmuted - handle that however you need to
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment