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

How to get user's ip address in JavaScript

How to make a static http server in nodejs using express

Array concat method in JavaScript

What is 'this.' keyword in JavaScript

How to create promises in JavaScript