ios – 移动平台上的Web Audio API内存泄漏

我正在使用一个将使用音频的应用程序,我正处于研究阶段,决定是否在支持它的设备上使用Web Audio API.我已经安装了一个非常简单的测试台,它加载了一个MP3精灵文件(大小为600kB),有一个播放和暂停按钮,还有一个破坏按钮,这应该在理论上允许GC回收Web Audio API实现中使用的内存.但是,由于内存不足的异常,加载和破坏〜5次iOS崩溃后.

我在XCode仪器中分析了MobileSafari,确实是MobileSafari不断地消耗了内存.此外,600kb的MP3在解码时可以使用〜80-90MB的内存.

我的问题是 – 当使用Web Audio API解码音频数据时,为什么内存使用这么大,为什么内存从未被回收?从我的理解,解码是浏览器的异步操作,因此大概发生在单独的线程上?浏览器分离线程是否可能永远不会释放解码过程中使用的内存?

我的代码在下面,任何帮助/解释非常感谢:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Web Audio Playground</title>
</head>
<body>
<button id="load">
    Load
</button>
<button id="play">
    Play
</button>
<button id="pause">
    Pause
</button>
<button id="destroy">
    Destroy
</button>
<script type="application/javascript">
    (function () {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;

        var loadButton = document.getElementById('load'),playButton = document.getElementById('play'),pauseButton = document.getElementById('pause'),destroyButton = document.getElementById('destroy'),audioContext = new window.AudioContext(),soundBuffer = null,soundSource = null;

        loadButton.addEventListener('click',function () {
            var request = new XMLHttpRequest();
            request.open('GET','live-sprite.mp3',true);
            request.responseType = 'arraybuffer';

            // Decode asynchronously
            request.onload = function () {
                audioContext.decodeAudioData(request.response,function (buffer) {
                    soundBuffer = buffer;
                });
            };
            request.send();
        });

        playButton.addEventListener('click',function () {
            soundSource = audioContext.createBufferSource();
            soundSource.buffer = soundBuffer;
            soundSource.connect(audioContext.destination);
            soundSource.start(0);
        });

        pauseButton.addEventListener('click',function () {
            if (soundSource) {
                soundSource.stop(0);
            }
        });

        destroyButton.addEventListener('click',function () {
            if (soundSource) {
                soundSource.disconnect(0);
                soundSource = null;
                soundBuffer = null;
                alert('destroyed');
            }
        });
    })();

</script>
</body>
</html>

解决方法

内存很大,因为Web Audio API将您的小型MP3解码为32位LPCM,这将为您提供每通道每分钟10MB的数量.

所以一个4分钟的立体声MP3最终会像80MB这样的东西.

只要你的应用程序持续到解码的AudioBuffer,这个内存不能被回收.所以只要你有一个参考(在你的情况下,soundBuffer),该内存不能被释放.如果是,您无法播放音频.

以上是来客网为你收集整理的ios – 移动平台上的Web Audio API内存泄漏全部内容,希望文章能够帮你解决ios – 移动平台上的Web Audio API内存泄漏所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。