Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

For our browser based games we want to play music right away, which is not allowed in modern browsers.

The browser requires that the first media play action is preceded by a user gesture (click etc). We use the following workaround: The script listens globally on a gesture event and then plays an empty audio once. This gives us permissions to play audio for the rest of the windows lifetime.

1
2
3
4
5
6
7
let getAudioPermissionsOnce = () => {
  new Audio().play().then(() => {
    console.log('Got permission to play audio files.');
    window.removeEventListener('click', getAudioPermissionsOnce);
  });
}
window.addEventListener('click', getAudioPermissionsOnce);

Version with multiple events.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let eventListeners = ['click', 'keydown', 'touchstart', 'pointerdown'];
let getAudioPermissionsOnce = () => {
  new Audio().play().then(() => {
    console.log('Got permission to play audio files.');
    eventListeners.forEach((e) => {
      window.document.removeEventListener(e, getAudioPermissionsOnce);
    });
  });
};
eventListeners.forEach((e) => {
  window.document.addEventListener(e, getAudioPermissionsOnce);
});