使用 WebAudio 的内存高效代码 API

Memory Efficient Code with WebAudio API

我正在开发 HTML5 游戏并使用 Web Audio API 制作声音。我有一个问题,随着游戏的进行,声音开始变慢,而且游戏也开始感到抽搐,我猜这是由于 java-script GC 做内存 cleanup.There 是我正在玩的两种声音游戏: 1) 不断循环的背景音 2) 跳跃音、击中音等因游戏中发生频率较高的事件而出现。例如:从枪中发射多发子弹。 不确定我做错了什么,请帮忙。请参考以下代码

function play(){
    this.startTime = this.actx.currentTime;
    this.soundNode = this.actx.createBufferSource();
    this.soundNode.buffer = this.buffer;
    this.soundNode.connect(this.volumeNode);

    //If there's no reverb, bypass the convolverNode
    if (this.reverb === false) {
        this.volumeNode.connect(this.panNode);
    }
    //If there is reverb, connect the `convolverNode` and apply
    //the impulse response
    else {
        this.volumeNode.connect(this.convolverNode);
        this.convolverNode.connect(this.panNode);
        this.convolverNode.buffer = this.reverbImpulse;
    }

    this.panNode.connect(this.actx.destination);
    this.soundNode.loop = this.loop;

    this.soundNode.playbackRate.value = this.playbackRate;
    this.soundNode.start(
        this.startTime,
        this.startOffset % this.buffer.duration
    );
    this.playing = true;
 }

除了使用卷积器(这可能非常昂贵并且在低端设备上导致性能不佳)之外,您的代码中没有任何内容特别占用内存。不过我会试试这个:

  1. 尝试禁用您的音频(不要 运行 任何音频代码,不要只是静音)。您的游戏视觉效果仍然存在问题吗?如果是这样,那不是您的音频问题。

  2. 尝试 运行 处理您的音频,但始终 运行 不使用卷积器。如果卡顿消失,卷积器就是你的罪魁祸首。我唯一能想到的就是尝试只设置卷积缓冲区一次,而不是每次调用 play()。

  3. 尝试 运行在 Chrome 开发工具(JS、内存、画图等)中使用不同的配置文件,并尝试找出卡顿的来源。 https://developer.chrome.com/devtools/docs/cpu-profiling

祝你好运!