Question

I've followed a pattern to attach sound to an object using Webaudio. It works well, however if I generate multiple items on a page and attach this script I get a console.log indicating that I've exceed the maximum number of audioContexts available per page.

My understanding is that the line declares the audioContext attaches to the window's AudioContext, not declares a new one. How might I ask the window if it already has an AudioContext and simply add audio nodes to its graph?

var that = this
  , audioContext = window.AudioContext || window.webkitAudioContext;

if (!audioContext) {
  console.warn("Web Audio API not supported in this browser.");
  return;
}

this.context = new audioContext();
Was it helpful?

Solution

I'm not totally sure I understand your problem. Is there a reason why you can't just create a single audio context at the top of your script and then have the rest of your code refer to it?

For the sake of providing an answer anyway, you could do something like this:

var getContext = function() {
  var ac = null;
  if ( !window.AudioContext && !window.webkitAudioContext ) {
    console.warn('Web Audio API not supported in this browser');
  } else {
    ac = new ( window.AudioContext || window.webkitAudioContext )();
  }
  return function() {
    return ac;
  };
}();

Then, every time you need a context, you just call this function:

var ctx = getContext(),
  osc = ctx.createOscillator();
osc.connect(ctx.destination);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top