Search code examples
javascriptweb-audio-apiobservers

Using the WebAudio API, is polling the only way to observe changes to the value of an AudioParam?


Am I correct in thinking that we are reduced to polling AudioParams to observe changes to their value?

An AudioParam is created as a property of an AudioNode, eg:

var gainNode = audioContext.createGain();
var param = gainNode.gain;

The param is an object with a bunch of methods and properties for controlling the gain of the node. To observe changes, we need to observe the param's 'value' property.

The problem is Object.observe fails silently:

Object.observe(param, function(changes){
    console.log(changes);
});

Here the callback is never called.

You can also reconfigure the 'value' property as a getter/setter and call the observing code whenever value is set – but that also fails silently. The property is configurable, and you can set a value on it, but the audio node does not appear to use the getter to get the value, so it doesn't use the value we set. I think it should be non-configurable for this reason.

I can understand why these methods would be undesirable – AudioParam values can get updated at the sample rate, so these observers could potentially be called thousands of times per second.

So the question is, are we reduced to polling to observe changes to the value of an AudioParam object (albeit on requestAnimationFrame, but still, polling), or is there a better way?

(I asked this question a few days ago on the public-audio mailing list: http://lists.w3.org/Archives/Public/public-audio/2014JulSep/0054.html. No replies so far.)


Solution

  • We are not sure on how to do that, as this has serious performances implications. In the meantime, I suggest that you just reimplement an AudioParam wrapper that can give you value on the main thread.