Question

Im researching into WebAudio API and HTML5/Javascript as a learning process, i've looked into the code of some peoples project to try and break it down as a kind of learning curve but something is puzzling me. The code below is some JS of Audio on a play/stop button along with a LOWPASS filter and Quality slider, how would this be changed to Autoplay instead of the play/stop button? Its confusing me like crazy.

var QUAL_MUL = 30;

function FilterSample() {
  this.isPlaying = false;
  loadSounds(this, {buffer: '02.mp3'});
};


FilterSample.prototype.play = function() {
  // Create the source.
  var source = context.createBufferSource();
  source.buffer = this.buffer;
  // Create the filter.
  var filter = context.createBiquadFilter();
  filter.type = filter.LOWPASS;
  filter.frequency.value = 5000;
  // Connect source to filter, filter to destination.
  source.connect(filter);
  filter.connect(context.destination);
  // Play!
  source.start(0);
  source.loop = true;
  //!-- THIS DOESN'T WORK source.autoplay = true;
  // Save source and filterNode for later access.
  this.source = source;
  this.filter = filter;
};


// PAUSE Button Function
  FilterSample.prototype.stop = function() {
  this.source.stop(0);
 };

// Play Button Toggle Function
FilterSample.prototype.toggle = function() {
  this.isPlaying ? this.stop() : this.play();
  this.isPlaying = !this.isPlaying;
}; 

FilterSample.prototype.changeFrequency = function(element) {

  var minValue = 40;
  var maxValue = context.sampleRate / 2;

  var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;

  var multiplier = Math.pow(2, numberOfOctaves * (element.value - 1.0));

  this.filter.frequency.value = maxValue * multiplier;
};

FilterSample.prototype.changeQuality = function(element) {
  this.filter.Q.value = element.value * QUAL_MUL;
};

FilterSample.prototype.toggleFilter = function(element) {
  this.source.disconnect(0);
  this.filter.disconnect(0);

  if (element.checked) {

    this.source.connect(this.filter);
    this.filter.connect(context.destination);
  } else {

    this.source.connect(context.destination);
  }
};

Cheers in advance if you can help me understand this

Was it helpful?

Solution

You need to modify loadSounds to accept a callback function that gets executed when all the sounds have been fetched/loaded/whatever.

Then just change your constructor to:

function FilterSample() {
  this.isPlaying = false;
  loadSounds(this, {buffer: '02.mp3'}, function() {
    this.play();
  }.bind(this));
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top