Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AudioContext not allowed to start in ToneJS (Chrome)

Using ToneJS in Chrome, I frequently get this error message: "The AudioContext was not allowed to start. It must be resume (or created) after a user gesture on the page."

For example, with the code below, I get this message every time I use ctrl-r or ctrl-f5 to refresh the page.

I can get it working again by typing Tone.context.resume() into the console, but that gets pretty repetitive. Why this is going on, and how can I stop it?

var keyToPitch = { "z":"C3", "s":"C#3", "x":"D3", "d":"D#3", "c":"E3", "v":"F3", "g":"F#3", "b":"G3", "h":"G#3", "n":"A3", "j":"A#3", "m":"B3", ",":"C4" }


var synth = new Tone.PolySynth(6, Tone.Synth, {
    "oscillator" : {
        "type": "sawtooth",
        "partials" : [0, 2, 3, 4],
        }
    }).toMaster();


 window.addEventListener('keydown', this.onkeydown)
 window.addEventListener('keyup', this.onkeyup)

function onkeydown(e){
   synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)
}
function onkeyup(e){
    synth.triggerRelease(keyToPitch[e.key])
}
like image 546
drenl Avatar asked Sep 20 '25 13:09

drenl


1 Answers

It appears that Chrome is instituting a policy to require user interaction to use AudioContext so that sites can't intrusively play audio without the user initiating it.

Fortunately, you are already using user input to trigger the audio via keydown and keyup events. Instead of calling Tone.context.resume() manually, you can hook up the events to initiate resume(), like this:

function onkeydown(e){
  Tone.context.resume().then(() => {
    synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)
  });
}
function onkeyup(e){
  Tone.context.resume().then(() => {
    synth.triggerRelease(keyToPitch[e.key])
  });
}
like image 177
Kevin Qi Avatar answered Sep 23 '25 03:09

Kevin Qi