web audio api 播放完后会清空一个源节点吗?

does the web audio api clear out a source node after it finishes playing?

当用户单击按钮时会播放声音,如果他再次单击按钮,则会播放相同声音的新实例。

我通过在每次点击时将一个新的源节点连接到音频上下文来做到这一点。

现在假设用户单击按钮 1 小时,是否每个已完成播放的源节点都被删除或保持与音频上下文的连接?

如果 BufferSourceNode 仍连接到音频上下文,则不会被删除。您可以使用 Firefox Web Audio 开发工具或安装 Audion Chrome 扩展来检查这一点。

您可以在 BufferSourceNode 中添加一个 onended 函数,以便在使用后断开连接。然后,只要没有其他对象引用该缓冲区源节点,它就会被垃圾收集器清除。

来源:https://developer.mozilla.org/en-US/docs/Web/API/AudioScheduledSourceNode/onended

这里是 relevant specs:

The following behaviors provide a normative description of the conditions under which an AudioNode is alive, meaning that it MUST be retained in the graph by an implementation. Where these conditions do not apply, AudioNodes MAY be released by an implementation.

There are several types of references:

  1. A normal reference obeying normal garbage collection rules.

  2. A playing reference for AudioBufferSourceNodes, MediaElementAudioSourceNodes, MediaStreamAudioSourceNodes and OscillatorNodes. These nodes maintain a playing reference to themselves while they are currently playing.

  3. A connection reference which occurs if another AudioNode is connected to one or more of its inputs. Connections to a node’s AudioParams do not imply a connection reference.

  4. A tail-time reference which an AudioNode maintains on itself as long as it has any internal processing state which has not yet been emitted. For example, a ConvolverNode has a tail which continues to play even after receiving silent input (think about clapping your hands in a large concert hall and continuing to hear the sound reverberate throughout the hall). Some AudioNodes have this property. Please see details for specific nodes.

  5. MediaStreams keep a MediaStreamAudioSourceNode alive as long as the underlying MediaStreamTrack that is playing through the MediaStreamAudioSourceNode has not ended (as per [mediacapture-streams]).

  6. HTMLMediaElements keep their associated MediaElementAudioSourceNode alive as long as the HTMLMediaElement is in a state where audio could ever be played in the future.

例如,在 AudioBufferSourceNode 的情况下,因为它没有输入 (3),所以没有 tail-time( 4), 没有链接到外部 MediaStream(5) 或 MediaElement(6), 如果你没有在你的 js 代码中保留对节点的任何引用(1), 并且节点已经完成播放(2), 那么它可以从图表中删除,然后进行垃圾收集。


另请注意,大多数 source 节点无论如何都只有很少的指纹。

如果我们再次以 AudioBufferSourceNodes 为例,那么您必须了解它们不会复制 AudioBuffer,它们只是参考一下。
因此,从同一个 AudioBuffer 创建数千个 AudioBufferSourceNodes 就可以了。

然而,从相同的 ArrayBuffer 或从中创建数千个 ArrayBuffersAudioBuffers同一个文件,或者两者都不好,所以请确保当您处理点击事件时,您所做的只是从先前存在的 创建一个新的 AudioBufferSourceNode音频缓冲区.