如何使用web audio api重新触发(扼流)声音

时间:2014-04-23 16:16:21

标签: audio web-audio

我很好奇我怎么能做一些叫做“窒息”的事情。在网络音频api。当我使用键发出声音时,如果再次按下该键,我希望它停止声音再次播放。知道怎么做吗?

到目前为止我的代码:

    $(document).on("keydown", function(e) {
console.log(e);
switch (e.keyCode) {
    case 81:  // Q 
        playKick(BUFFERS.kick);
    break;
}
})

function playKick(instrument) {
    source1 = context.createBufferSource();
    source1.buffer = instrument;
    source1.loop = true;
    source1.connect(context.destination);
    if (!source1.start)
      source1.start = source1.noteOn;
    source1.start(0);
  }

1 个答案:

答案 0 :(得分:2)

您想要保留对当前播放声音的引用。因此,需要在playKick范围之外提供。然后,在playKick内,您可以在创建新声音并将其分配给该全局变量之前,在旧声音上调用stopnoteOff

类似的东西:

var current;

$(document).on('keydown', function( e ) {
  console.log(e);
  switch (e.keyCode) {
    case 81:
      playKick(BUFFERS.kick);
    break;
  }
});

function playKick( instrument ) {
  var source = context.createBufferSource();
  source.buffer = instrument;
  source.loop = true;
  source.connect(context.destination);
  if ( current ) {
    if ( !current.stop ) {
      current.stop = current.noteOff;
    }
    current.stop(0);
  }
  if ( !source.start ) {
    source.start = source.noteOn;
  }
  source.start(0);
  current = source;
}

当然,肯定有更好的方法来组织这个 - 但希望这会让你开始。