How to resume a suspended web audio api context

A quick JavaScript function to maneuver around Google chrome, Firefox and safari web audio context suspension state

Starting from chrome v{xx} Google chrome, Mozilla Firefox and Apple safari web browsers automatically suspend html5 web audio contexts if they start without any user gesture they can only be resumed by a user gesture it's a measure implemented to improve overall user experience.

context.state property stores the state of the audio context when it's suspended it's value changes to "suspended".
in order to implant a maneuver first check the state of the context should it be suspended literate an array of events for each add an event listener on the document body and remove the event if one of the events has been triggered by the user

let unlockAudio = function(context) {
    if (context.state === 'suspended') {
        let events = ['touchstart', 'touchend', 'mousedown', 'keydown']
        let unlock = function() {
            events.map((event) => {
                document.body.removeEventListener(event, unlock)
            })
            context.resume()
        }

        events.map((event) => {
            document.body.addEventListener(event, unlock, false)
        })
    }
}

Comments

Popular posts from this blog

Open-graph meta data tags introdution

What is 'this.' keyword in JavaScript

How to create zip archives in nodejs

what is 'array.includes' function in JavaScript

How to build a twitter retweet bot using JavaScript