2015-03-13 232 views
0

我創建了一個對象,它連續從麥克風讀取輸入,但我遇到了一些麻煩。我需要能夠暫停並啓動它,所以我已經實現了這些方法,但問題在於,在舊手機(Galaxy Y)上它第一次啓動時效果很好,但在暫停後由於OutOfMemoryException,它再次啓動它會迅速崩潰。AudioRecord內存不足異常

@Override 
public void run() { 
    while (mIsRunning) { 
     synchronized (mThread) { 
      while (mIsPaused) { 
       try { 
        mThread.wait(); 
       } catch (InterruptedException e) { 
       } 
      } 
     } 
     double sum = 0; 
     int readSize = mRecorder.read(mBuffer, 0, mBuffer.length); 

     if (readSize > 0) { 
      short[] samples = new short[readSize]; 
      for (int i = 0; i < readSize; i++) { 
       sum += mBuffer[i] * mBuffer[i]; 
       samples[i] = mBuffer[i]; 
      } 

      final int amplitude = (int) Math.sqrt((sum/readSize)); 

      Message message = new Message(); 
      message.arg1 = amplitude; 
      message.arg2 = readSize; 
      message.obj = samples; 
      message.what = 0; 

      if (mHandler != null) 
       mHandler.sendMessage(message); 

     } 

    } 

} 

public void start() { 
    if (!mIsRunning) { 
     mIsRunning = true; 
     mThread.start(); 
    } else synchronized (mThread) { 
     mIsPaused = false; 
     mThread.notifyAll(); 
    } 

    mRecorder.startRecording(); 

} 

public void pause() { 
    synchronized (mThread) { 
     mIsPaused = true; 
    } 

    mRecorder.stop(); 

} 

所以,在第一時間一切運作良好,但之後,我呼籲AudioRecord停止(),並開始讀取輸入我又很快耗盡內存。有想法該怎麼解決這個嗎?我正在考慮不停止錄製,只是不通過處理程序發送數據,但我不知道。謝謝。

回答

0

解決方案在每次暫停時銷燬(並釋放)AudioRecord對象,並在每次啓動時重新創建它。