mohayonao / web-audio-engine

Pure JS implementation of the Web Audio API
243 stars 32 forks source link

Looping does not work. #48

Closed tustin2121 closed 7 years ago

tustin2121 commented 7 years ago

I'm writing something that requires looping to work, and I chose this library because it seems to be the most complete implementation. However, looping simply does not function. I put together the most basic case, playing a 2 minute song, like so:

let src = audioCtx.createBufferSource();
src.buffer = buf;
src.loop = true;
src.loopStart = 10;
src.loopEnd = 15;
src.connect(audioCtx.destination);
src.start(0, 0);

But the song does not loop back around to the 10 second mark from the 15 second mark. I don't know exactly how the DSP functions work, but it looks for all the world like the DSP only considers looping if the loopEnd is set to the very end of the buffer length, and that is not how the actual Web Audio API works, and that's not going to work for my purposes either.

tustin2121 commented 7 years ago

I've managed to fix the problem like so:

This part of AudioBufferSourceNode.js (line 81):

  if (bufferDuration <= phaseTime) {
    if (this._loop) {
      if (0 < this._loopEnd && this._loopEnd <= phaseTime) {
        phase = Math.max(0, Math.min(this._loopStart, bufferDuration)) * bufferSampleRate;
      }
    } else {
      this.dspEmitEnded();
      break;
    }
  }

I've changed to this:

if (this._loop) {
    if (0 < this._loopEnd && this._loopEnd <= phaseTime) {
      phase = Math.max(0, Math.min(this._loopStart, bufferDuration)) * bufferSampleRate;
    }
  }

  if (bufferDuration <= phaseTime) {
    //  else {
      this.dspEmitEnded();
      break;
    // }
  }

This loops the audio as expected (though it may be a few milliseconds off with the timing, which isn't nearly as big of a deal breaker as not having looping at all).

mohayonao commented 7 years ago

Thanks! I've fixed this problem.

You can test looped playing in demo page. https://mohayonao.github.io/web-audio-engine/demo/#test_loop

mreinstein commented 7 years ago

@mohayonao can you publish a new version to npm? It looks like web-audio-engine is on a version published 6 months ago (0.11.0)

https://www.npmjs.com/package/web-audio-engine

mohayonao commented 7 years ago

oooo. I forgot to publish to npm. thanks!