Javascript计时器内存泄漏

时间:2015-04-13 13:39:08

标签: javascript memory memory-leaks web-audio

我一直在做一个画布游戏,并遇到了一些涉及内存泄漏的问题。我认为这个问题与渲染和删除实体有关,但我运行的代码没有渲染任何东西,它看起来像音频调度对象本身导致泄漏。这个问题导致音频开始噼啪作响并在一段时间后切断。游戏仍然渲染,但音频停止 - 我也注意到角色的拍摄速度变慢了(拍摄时间与调度功能中的音符一起安排)。

Link to game

我用来处理音频的代码来自 A Tale of Two Clocks' tutorial 。当我在chrome上运行节拍器代码并进行时间线记录时,堆分配上升了。

为什么此代码会导致内存泄漏?它看起来很好。计时器ID设置为空?

图片1 :节拍器的堆时间线本身

http://i.imgur.com/IuYIcxj.png

图片2 :我的应用程序的时间轴只运行节拍器功能(没有游戏实体)

http://i.imgur.com/vGCbI1H.png

图片3 :我的应用正常运行

http://i.imgur.com/WbrocOH.png

这是代码

function init(){
  var container = document.createElement( 'div' );
  // CREATE CANVAS ... ...
  audioContext = new AudioContext();
  requestAnimFrame(draw);    

  timerWorker = new Worker("js/metronomeworker.js");
  timerWorker.onmessage = function(e) {
    if (e.data == "tick") {
      // console.log("tick!");
      scheduler();
    }
    else {
      console.log("message: " + e.data);
    }
  };
  timerWorker.postMessage({"interval":lookahead});
}

function nextNote() {
  // Advance current note and time by a 16th note...
  var secondsPerBeat = 60.0 / tempo;    // Notice this picks up the CURRENT 
                                        // tempo value to calculate beat length.
  nextNoteTime += 0.25 * secondsPerBeat;    // Add beat length to last beat time

  current16thNote++;    // Advance the beat number, wrap to zero
  if (current16thNote == 16) {
      current16thNote = 0;
  }
}

function scheduleNote( beatNumber, time ) {
  // push the note on the queue, even if we're not playing.
  notesInQueue.push( { note: beatNumber, time: time } );

  if ( (noteResolution==1) && (beatNumber%2))
    return; // we're not playing non-8th 16th notes
  if ( (noteResolution==2) && (beatNumber%4))
    return; // we're not playing non-quarter 8th notes

  // create an oscillator    //   create sample
  var osc = audioContext.createOscillator();
  osc.connect( audioContext.destination );
  if (beatNumber % 16 === 0)    // beat 0 == low pitch
    osc.frequency.value = 880.0;
  else if (beatNumber % 4 === 0 )    // quarter notes = medium pitch
    osc.frequency.value = 440.0;
  else                        // other 16th notes = high pitch
    osc.frequency.value = 220.0;

  osc.start( time );              //sound.play(time)
  osc.stop( time + noteLength );  //   "      "
}

function scheduler() {
  // while there are notes that will need to play before the next      interval, 
  // schedule them and advance the pointer.
  while (nextNoteTime < audioContext.currentTime + scheduleAheadTime ) {
    scheduleNote( current16thNote, nextNoteTime );
    nextNote();
  }
}

function play() {
isPlaying = !isPlaying;

if (isPlaying) { // start playing
    current16thNote = 0;
    nextNoteTime = audioContext.currentTime;
    timerWorker.postMessage("start");
    return "stop";
} else {
    timerWorker.postMessage("stop");
    return "play";
}
}

Metronome.js:

var timerID=null;
var interval=100;

self.onmessage=function(e){
  if (e.data=="start") {
    console.log("starting");
    timerID=setInterval(function(){postMessage("tick");},interval)
  }
  else if (e.data.interval) {
    console.log("setting interval");
    interval=e.data.interval;
    console.log("interval="+interval);
    if (timerID) {
      clearInterval(timerID);
      timerID=setInterval(function(){postMessage("tick");},interval)
    }
  }
  else if (e.data=="stop") {
    console.log("stopping");
    clearInterval(timerID);
    timerID=null;
  }
};

我如何在scheduleNote()中安排声音(和拍摄):

if (beatNumber % 4 === 0) {
    playSound(samplebb[0], gainNode1);
 }
if (planet1play === true) {
    if (barNumber % 4 === 0)
        if (current16thNote % 1 === 0) {
            playSound(samplebb[26], planet1gain);
        }
}
if (shootx) {
    //  Weapon 1
    if (gun === 0) {
        if (beatNumber === 2 || beatNumber === 6 || beatNumber === 10 || beatNumber === 14) {
            shoot(bulletX, bulletY);
            playSound(samplebb[3], gainNode2);
        }
    }

更新

即使我在没有呈现或更新任何内容的情况下运行游戏,音频仍然存在问题 Here 在速度较慢的机器上情况更糟。

不知道为什么会发生这种情况,某种音频缓冲问题?有人有主意吗?

2 个答案:

答案 0 :(得分:1)

如果连续调用setInterval命令,则存在运行多个start的风险。如果他们是,他们会堆积起来,并解释为什么记忆力在​​增加。

我建议进行以下更改。没有你可以简单地检查start方法中是否存在timerID,但集中方法将有助于跟踪。可以使用clearInterval()参数调用null,但不会忽略它。

所以实质上:

var timerID = null;
var interval = 100;

function tickBack() {           // share callback for timer
    postMessage("tick")
}

function startTimer() {             // centralize start method
    stopTimer();                    // can be called with no consequence even if id=null
    timerID = setInterval(tickBack, interval)
}

function stopTimer() {              // centralize stop method
    clearInterval(timerID);
    timerID = null;
}

onmessage = function(e){

  if (e.data === "start") {
    startTimer();
  }
  else if (e.data === "stop") {
    stopTimer()
  }
  else if (e.data.interval) {
    interval = e.data.interval;
    if (timerID) startTimer();
  }
};

答案 1 :(得分:0)

卫生署!我发现了问题!在我的应用程序中,我创建了一个振荡器,而不是使用它,这填补了音频上下文

var osc = audioContext.createOscillator();
osc.connect( audioContext.destination );

http://users.sussex.ac.uk/~bc216/AX11/