Web音频api振荡器的内存泄漏 [英] Memory leak with web audio api oscillator

查看:85
本文介绍了Web音频api振荡器的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://codepen.io/superuntitled/pen/EjZOjw/?editors= 001

我有一个小型Web仪器(请参阅上面的链接),该仪器存在内存泄漏,并且不确定如何插入.

I have a little web instrument (see link above) that has a memory leak, and I am unsure how to plug it.

当元素悬停在上面时(其中有数百个),将调用以下函数.

The following function is called when an element is hovered over (there are a couple hundred of these).

function tone(id, freq, tonelength) {

  gainNodes.id = audioCtx.createGain();
  osc.id = audioCtx.createOscillator();
  osc.id.connect(gainNodes.id);
  // set frequency and gain
  osc.id.frequency.value = freq;
  osc.id.start(0);

  gainNodes.id.connect(audioCtx.destination);

  gainNodes.id.gain.linearRampToValueAtTime(.1, audioCtx.currentTime);

  gainNodes.id.gain.linearRampToValueAtTime(0, audioCtx.currentTime + parseFloat(tonelength));

}

我认为正在创建重复的振荡器,但是不确定如何检查这种情况,或者如何避免这种情况.

I think that duplicate oscillators are being created, but am not sure how to check if this is the case, or how to avoid it.

我有一种感觉,应该检查振荡器是否已经存在,并运行增益,但是我不确定如何做到这一点.

I have a feeling I should check to see if the oscillator already exists, and just run the gain, but I am not sure how to do that.

在尝试使用振荡器后,我试图将其停止,但这似乎并不能阻止泄漏:

I have tried to stop the oscillator after it's duration, but this does not seem to stop the leak: http://codepen.io/superuntitled/pen/rVmqYX?editors=001

osc.id.stop(audioCtx.currentTime + parseFloat(tonelength));

关于如何实现此目标的任何想法?

Any thoughts on how this could be done?

推荐答案

带有osc.id的东西有点奇怪,因为您将id设置为属性名称而不是osc[ id ] –但保留了该部分另外,您想将其添加到tone()函数的底部:

The thing with osc.id is a little weird, since you're setting id as a property name instead of osc[ id ] – but leaving that part aside, you'd want to add this to the bottom of your tone() function:

var current = osc.id;

current.stop( audioCtx.currentTime + 2 );

current.onended = function() {
  current.disconnect();
};

基本上是说"2秒后停止播放,完成后,断开与AudioContext的连接".

That basically says "Stop playing after 2 seconds, and when you're done, disconnect yourself from the AudioContext".

如果id是动态分配给osc的(例如osc[ id ]),那么您可能还需要delete osc[ id ] –但这似乎每次使用tone()调用时都会被覆盖.您现在拥有的方式–因此旧的振荡器应该有资格进行垃圾收集.

If id was dynamically assigned to osc (e.g. osc[ id ]), then you'd likely also need to delete osc[ id ] – but that seems to just be getting overridden each time tone() is called with the way you have it now – so the old oscillator should become eligible for garbage collection.

使用current变量的原因是,到onended触发时,osc.id可能已经被重新分配了-因此您需要引用原始振荡器.

The reason for the current variable is that by the time onended fires, osc.id will likely have been reassigned – so you need a reference to the original oscillator.

希望有帮助.

这篇关于Web音频api振荡器的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆