Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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