Search code examples
javascripthtmlweb-audio-api

Why does the stop method in AudioBufferNode destroy it?


We know that when you invoke #.stop() on an AudioBufferNode, you cannot then #.start(). Why is the behavior so?

This issue came up when playing around with WebAudio API as we all find out sooner or later when trying to implement pause functionality. What piqued my interest was, sure, I understand that it's a stream and you can't simple "pause" a stream. But why does it get destroyed? Internally, is there not a pointer to the data, or does the data simply get pushed to the destination and forgotten about by the buffer?


Solution

  • You're not calling .stop() on an AudioBuffer, you're calling .stop() on a BufferSourceNode - the AudioBuffer can be used multiple times.

    The short version is it's an optimization that allows for fire-and-forget playback of buffers in a very lightweight way - you can build a higher level media player around it, but in and of itself BufferSourceNodes are very lightweight. The sound data itself is not forgotten, and can be reused - in fact, used simultaneously by other BufferSourceNodes - because it's in the separate AudioBuffer object.