Вопрос

I'm curious how I can do something called a "choke" in web audio api. When I play a sound using a key, if that key is pressed again, I want it to stop the sound and play it again. Any idea how to do this?

My code so far:

    $(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);
  }
Это было полезно?

Решение

You want to keep a reference to the currently-playing sound. So that needs to be available outside the scope of playKick. Then, within playKick, you call stop or noteOff on the old sound before creating the new one and assigning it to that global var.

Something like:

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

Granted, there are certainly better ways to organize this — but hopefully this'll get you started.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top