chrisguttandin / standardized-audio-context

A cross-browser wrapper for the Web Audio API which aims to closely follow the standard.
MIT License
679 stars 33 forks source link

no sound at page load or on event #972

Closed pkasson closed 3 years ago

pkasson commented 3 years ago

if a button is clicked and sound played, it works. if an event comes in to the page (web socket for example) and sound is played for that event, no sound is heard.

chrisguttandin commented 3 years ago

Hi @pkasson, in order to really understand the problem it would be great if you could provide a code snippet which reproduces the problem. It would also be good to know which browser you're using.

From what you're describing I guess it's the autoplay policy which is causing the effect that you're describing. If it's the autoplay policy then there is unfortunately no way to avoid it. If it would be possible to avoid it, it wouldn't make sense anymore. :-) It's even spec compliant.

pkasson commented 3 years ago

Sorry, was going to leave a snippet ... it was early .. :)

I do believe I found that as well - the autoplay policy, and certainly for Safari. You need to allow playing to occur, but I wonder, just like on iPhone, is there a way to determine if that permission is not enabled and prompt to enable it ?

chrisguttandin commented 3 years ago

An AudioContext is suspended by default. But it will have the running state when it was allowed to start. A possible solution would be to wait for that statechange to happen and if it doesn't occur after a while it's safe to assume the context will not start by itself.

Maybe something like that works for you.

const audioContext = new AudioContext();

const timeout = setTimeout(() => {
    audioContext.onstatechange = null;

    // Oh no, a user gesture seems to be required to start the AudioContext.
}, 100);
audioContext.onstatechange = () => {
    if (audioContext.state === 'running') {
        clearTimeout(timeout);

        // Yeah, the AudioContext is running.
    }
};
pkasson commented 3 years ago

Awesome - thanks, will try that !