如何关闭在 iframe 中创建的所有 AudioContext?

How can I close all AudioContexts created within an iframe?

我正在开发一个网络应用程序,用户可以在其中编写网络音频代码并在 iframe 中预览他们的代码。每当更改输入文本区域时,iframe contentDocument 都会更新。

问题在于,当用户创建 AudioContext 时,会在旧上下文之上创建一个新上下文。这很快会导致创建过多的 AC,并且还会留下任何以前的 AC。

我需要一种方法来做类似

的事情
var iframe = document.getElementsByTagName("iframe")[0];

for (ac in iframe.contentWindow.audioContexts) {
    ac.close();
}

iframe.contentDocument.open();
iframe.contentDocument.write("//some new js/html code here");

这只是概念代码,显然不起作用。有没有办法有效地 'reload' 在 iframe 中创建的所有音频内容,就像重新加载标准网页时重新加载一样?

如何在 iframe 中重新加载所有 AudioContext

好吧,我找到了一个可能不是对每个人都是最佳的方法,但仍然有效。

基本上,您需要在 iframe 中模拟重新加载网站。

这可以通过多种方式完成,例如:

var iframe = document.getElementsByTagName("iframe")[0];

iframe.onload = function() {
    iframe.contentDocument.open();
    iframe.contentDocument.write("//some new js/html code here");
    iframe.contentDocument.close();
}
// src can be an empty string if you're not loading anything into it by default
iframe.src = your_iframe_src || "";

现在,这不是很快,它确实在我的应用程序中引入了一点延迟,但这可以通过使用单独的 rendering/validation 循环来解决。