我将如何/如何更改为自动播放?

时间:2014-02-16 20:44:45

标签: javascript html5 api web-audio autoplay

我正在研究WebAudio API和HTML5 / Javascript作为一个学习过程,我研究了一些人的项目代码,尝试将其作为一种学习曲线分解,但有些令我困惑的事情。下面的代码是播放/停止按钮上的一些JS音频以及LOWPASS过滤器和质量滑块,如何将其更改为自动播放而不是播放/停止按钮? 它让我很困惑。

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);
  }
};

如果你能帮助我理解这个,请提前干杯

1 个答案:

答案 0 :(得分:0)

您需要修改loadSounds以接受在获取/加载所有声音/其他任何声音时执行的回调函数。

然后只需将构造函数更改为:

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