Created
March 15, 2021 03:35
-
-
Save Finesse/92959ce907a5ba7ee5c05542e3f8741b to your computer and use it in GitHub Desktop.
Render audio context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Renders an offline audio context into an audio buffer. | |
* Considers timeout and suspension. | |
* | |
* The `context` argument is an instance of OfflineAudioContext. | |
*/ | |
function renderAudio(context) { | |
return new Promise((resolve, reject) => { | |
context.oncomplete = (event) => resolve(event.renderedBuffer) | |
// 3 tries to start the context when the page is in foreground | |
let resumeTriesLeft = 3 | |
const tryResume = () => { | |
context.startRendering() | |
switch (context.state) { | |
case 'running': | |
// The context has started calculating the audio signal. Start a plain timeout. | |
setTimeout(() => reject(new Error('Timeout')), 1000) | |
break | |
case 'suspended': | |
// Don’t count the tries when the page is in background | |
if (!document.hidden) { | |
resumeTriesLeft-- | |
} | |
if (resumeTriesLeft > 0) { | |
setTimeout(tryResume, 500) // There is a delay before a retry | |
} else { | |
reject(new Error('Suspended')) | |
} | |
break | |
} | |
} | |
tryResume() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment