Skip to content

restart audio context on interactions #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions wasm/index.html
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<!doctype html>
<html lang="en">
<script type="module">
import init from './bevy_game.js'
init()
</script>

<body style="margin: 0px;">
<script type="module">
import './restart-audio-context.js'
import init from './bevy_game.js'
init()
</script>
</body>

</html>
</html>
57 changes: 57 additions & 0 deletions wasm/restart-audio-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// taken from https://developer.chrome.com/blog/web-audio-autoplay/#moving-forward
(function () {
// An array of all contexts to resume on the page
const audioContextList = [];

// An array of various user interaction events we should listen for
const userInputEventNames = [
'click',
'contextmenu',
'auxclick',
'dblclick',
'mousedown',
'mouseup',
'pointerup',
'touchend',
'keydown',
'keyup',
];

// A proxy object to intercept AudioContexts and
// add them to the array for tracking and resuming later
self.AudioContext = new Proxy(self.AudioContext, {
construct(target, args) {
const result = new target(...args);
audioContextList.push(result);
return result;
},
});

// To resume all AudioContexts being tracked
function resumeAllContexts(event) {
let count = 0;

audioContextList.forEach(context => {
if (context.state !== 'running') {
context.resume();
} else {
count++;
}
});

// If all the AudioContexts have now resumed then we
// unbind all the event listeners from the page to prevent
// unnecessary resume attempts
if (count == audioContextList.length) {
userInputEventNames.forEach(eventName => {
document.removeEventListener(eventName, resumeAllContexts);
});
}
}

// We bind the resume function for each user interaction
// event on the page
userInputEventNames.forEach(eventName => {
document.addEventListener(eventName, resumeAllContexts);
});
})();