Skip to content

DynamicsCompressor.reduction

rtoy edited this page Apr 19, 2016 · 3 revisions

In WebAudioAPI Issue 243, the reduction parameter for the DynamicsCompressor node changed from an AudioParam to a plain float. As this change gets implemented, developers will need to support both the AudioParam version and the float version.

For something quick and dirty, you can do something like this:

var c = new AudioContext();
var dc = c.createDynamicsCompressor();
var reductionValue;
if (typeof dc.reduction === 'float') {
  reductionValue = dc.reduction;
} else {
  reductionValue = dc.reduction.value;
}

For a more complete and general solution use the following polyfill. Write your code assuming .reduction is a float value. Then, if the implementation still uses an AudioParam, your code will still work, without change.

!function() {

  var _isCompressorReductionAudioParam = 
    typeof (new OfflineAudioContext(1, 1, 44100)).createDynamicsCompressor().reduction 
    === 'object';
  
  AudioContext.prototype._createDynamicsCompressor =
    AudioContext.prototype.createDynamicsCompressor;
  OfflineAudioContext.prototype._createDynamicsCompressor =
    OfflineAudioContext.prototype.createDynamicsCompressor;

  AudioContext.prototype.createDynamicsCompressor =
  OfflineAudioContext.prototype.createDynamicsCompressor = function () {
    var compressor = this._createDynamicsCompressor();
    if (_isCompressorReductionAudioParam) {
      compressor._reduction = compressor.reduction;
      Object.defineProperty(compressor, 'reduction', {
        get: function () {
          return compressor._reduction.value;
        }
      });
    }
    return compressor;
  };
  
}();