I faced a browser policy problem "The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page." I wanted to execute that below code when page loaded. So, I tried to mock the user click gesture using a hidden button and load event listener but failed.
Is it possible??
let my_array = [];
function my_function() {
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let analyser = audioCtx.createAnalyser();
let oscillator = audioCtx.createOscillator();
oscillator.type = "triangle"; // Set oscillator to output triangle wave
oscillator.connect(analyser); // Connect oscillator output to analyser input
let gain = audioCtx.createGain();
let scriptProcessor = audioCtx.createScriptProcessor(4096, 1, 1);
analyser.connect(scriptProcessor); // Connect analyser output to scriptProcessor input
scriptProcessor.connect(gain); // Connect scriptProcessor output to gain input
gain.connect(audioCtx.destination); // Connect gain output to audiocontext destination
gain.gain.value = 0; // Disable volume
scriptProcessor.onaudioprocess = function (bins) {
bins = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatFrequencyData(bins);
for (var i = 0; i < bins.length; i = i + 1) {
my_array.push(bins[i]);
}
analyser.disconnect();
scriptProcessor.disconnect();
gain.disconnect();
};
// audioCtx.resume().then(() => {
// oscillator.start(0);
// });
oscillator.start(0);
}
Update
There is a way to enable sound permission for the site in Chrome (the lock icon in the address bar, then Site settings). Yet in this case you cannot query if the permission has been granted, and hasBeenActive is not set. So the solution below doesn't actually work, unless knowing for sure people have not given manual permission to the site to play sounds.
The old answer
Just for anyone else getting this warning and considering it annoying. There is a way to determine if the user has made a gesture by calling navigator.userActivation.hasBeenActive. In other words, if you create an AudioContext (or any other API that is restricted by this) only when this field is true, you will not get the warning.
More here: https://developer.mozilla.org/en-US/docs/Web/API/UserActivation/hasBeenActive - sticky activation (for AudioContext)
More here: https://developer.mozilla.org/en-US/docs/Web/API/UserActivation/isActive - transient activation (see the list of APIs in the last link)
And here: https://html.spec.whatwg.org/multipage/interaction.html#user-activation-gated-apis
And here: https://developer.mozilla.org/en-US/docs/Web/Security/User_activation