Skip to content

Instantly share code, notes, and snippets.

@Finesse
Created March 15, 2021 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Finesse/92959ce907a5ba7ee5c05542e3f8741b to your computer and use it in GitHub Desktop.
Save Finesse/92959ce907a5ba7ee5c05542e3f8741b to your computer and use it in GitHub Desktop.
Render audio context
/**
* 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