Html 使用WebAudio API的内存高效代码

Html 使用WebAudio API的内存高效代码,html,audio,web-audio-api,Html,Audio,Web Audio Api,我正在开发一个HTML5游戏,并使用Web音频API进行声音处理。我遇到了一个问题,随着游戏的进行,声音开始变慢,游戏也开始感觉到震动,我猜这是因为java脚本GC正在进行内存清理。我在游戏中玩的声音有两种类型: 1) 连续循环的背景声音 2) 跳跃声、撞击声等是由于游戏中经常发生的某些事件而产生的。例如:从枪中发射多发子弹。 不确定我做错了什么,请帮忙。请参考下面的代码 function play(){ this.startTime = this.actx.currentTime;

我正在开发一个HTML5游戏,并使用Web音频API进行声音处理。我遇到了一个问题,随着游戏的进行,声音开始变慢,游戏也开始感觉到震动,我猜这是因为java脚本GC正在进行内存清理。我在游戏中玩的声音有两种类型: 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;
 }

除了使用卷积器(卷积器可能非常昂贵,并且在低端设备上会导致糟糕的性能)之外,您的代码中没有特别突出的内存密集型代码。不过我还是要试试这个:

  • 尝试禁用音频(不要运行任何音频代码,不要将其静音)。你在游戏的视觉效果中还有janks吗?如果是这样,罪魁祸首不是你的音频

  • 尝试运行音频,但始终在没有卷积器的情况下运行。如果jank消失了,护卫者就是你的罪魁祸首。我唯一能想到的就是尝试只设置一次卷积器缓冲区,而不是每次调用play()

  • 尝试在Chrome开发工具中运行不同的配置文件(JS、内存、油漆等),并尝试找出janks的来源


  • 祝你好运

    谢谢Oskar,我会尝试一下,看看它是否解决了这个问题。谢谢:)