問題描述
我有一個 js 函數,用于使用音頻接口播放任何給定的聲音(為每個調用創建一個新實例).
I have a js function for playing any given sound using the Audio interface (creating a new instance for every call).
這工作得很好,直到大約第 32 次調用(有時更少).此問題與 Audio 實例的發布直接相關.我知道這一點是因為我已經讓 Chromium 中的 GC 有時間運行,它可以讓我再次播放另外 32 種左右的聲音.
This works quite well, until about the 32nd call (sometimes less). This issue is directly related to the release of the Audio instance. I know this because I've allowed time for the GC in Chromium to run and it will allow me to play another 32 or so sounds again.
這是我正在做的一個例子:
Here's an example of what I'm doing:
<html><head>
<script type="text/javascript">
function playSound(url) {
var snd = new Audio(url);
snd.play();
snd = null;
}
</script>
</head>
<body>
<a href="#" onclick="playSound('blah.mp3');">Play sound</a>
</body></html>
我也有這個,它適用于少于 32 個 playSound 調用的頁面:
I also have this, which works well for pages that have less than 32 playSound calls:
var AudioPlayer = {
cache: {},
play: function(url) {
if (!AudioPlayer.cache[url])
AudioPlayer.cache[url] = new Audio(url);
AudioPlayer.cache[url].play();
}
};
但這不適用于我想做的事情(用其他內容(來自單獨的文件)動態替換 div,這些內容有更多的聲音 - 1. 內存使用量很容易飆升,2. 很多聲音永遠不會玩).
But this will not work for what I want to do (dynamically replace a div with other content (from separate files), which have even more sounds on them - 1. memory usage would easily skyrocket, 2. many sounds will never play).
我需要一種立即釋放聲音的方法.是否有可能做到這一點?我沒有找到音頻接口的免費/關閉/卸載方法.
I need a way to release the sound immediately. Is it possible to do this? I have found no free/close/unload method for the Audio interface.
頁面將在本地查看,因此聲音的持續加載根本不是一個重要因素(而且大多數聲音都很短).
The pages will be viewed locally, so the constant loading of sounds is not a big factor at all (and most sounds are rather short).
推薦答案
這不是一個詳盡的答案,而是針對有沒有辦法強制chrome js引擎進行垃圾收集?"的問題,一個 chromium.org 的人回復了:
This is not an exhaustive answer, but to the question "Is there any way to force the chrome js engine to do garbage collection?", a chromium.org guy replied:
一般來說,不,設計使然. 出于測試目的,您可以通過一個標志在命令行上啟用 javascript 命令window.gc()"強制垃圾收集.
In general, no, by design. For testing purposes there is a flag you can pass on the command line to enable a javascript command "window.gc()" to force garbage collection.
--js-flags '--expose_gc'
<小時>
更新:但是,正如@plash 在下面的評論中指出的那樣,此標志將僅適用于調試版本.
UPDATE: However, as @plash noted in a comment below, this flag will only work in debug builds.
這篇關于Javascript強制GC收集?/強制釋放對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!