2017-08-20 58 views
0

我用AudioRecord編寫了一個用於從麥克風接收數據的標準代碼。這裏是我的代碼:AudioRecord在啓動後返回一些空數據

AudioReceiver() { 
    int minHardwareBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, 
      CHANNEL_CONFIG, AUDIO_FORMAT); 
    Log.d(TAG, "minHardwareBufferSize = " + minHardwareBufferSize); 
    int bufferSizeBytes = (minHardwareBufferSize > MIN_BUFFER_SIZE_BYTES) ? 
      minHardwareBufferSize : MIN_BUFFER_SIZE_BYTES; 
    bufferSizeShorts = bufferSizeBytes/2; 

    //резервируем буфер с запасом в 2 раза 
    audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, 
      SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSizeBytes * 2); 

    testStack = new short[bufferSizeShorts * 4]; 
    Arrays.fill(testStack, (short) 2000); 
} 


boolean startReceive() { 
    audioRecorder.startRecording(); 
    isReceiving = true; 
    int recordingState = audioRecorder.getRecordingState(); 
    Log.d(TAG, "recordingState = " + recordingState); 
    new Thread(receivingRunnable).start(); 
    return (recordingState == AudioRecord.RECORDSTATE_RECORDING); 
} 


boolean stopReceive() { 
    isReceiving = false; 
    audioRecorder.stop(); 
    int recordingState = audioRecorder.getRecordingState(); 
    Log.d(TAG, "recordingState = " + recordingState); 
    return (recordingState == AudioRecord.RECORDSTATE_STOPPED); 
} 


private Runnable receivingRunnable = new Runnable() { 
    @Override 
    public void run() { 
     int readCount = 0; 
     short[] dataBuffer = new short[bufferSizeShorts]; 
     while (isReceiving) { 
      testBusy = true; 
      for (int j = 0; j < 4; j++) { 
       readCount = audioRecorder.read(dataBuffer, 0, dataBuffer.length); 
       Log.d(TAG, "receive " + readCount + " bytes"); 
       System.arraycopy(dataBuffer, 0, testStack, bufferSizeShorts * j, readCount); 
      } 
      isReceiving = false; 
      testBusy = false; 
     } 
    } 
}; 

但我注意到,startReceive功能的第一次啓動後,在testStack緩衝區的開始,還有空的數據(約1000個樣本上的Nexus 4,看資料圖) 。

Data graph

AudioReceiver的初始化和推出startReceive之間需要很長的時間。什麼可能是問題的原因?

+0

您是否發現此問題的任何解決方案@solderingironmen?我遇到了同樣的問題。 –

+0

@KhatamNaayak,no。如果你遇到同樣的問題,請提出我的問題。 – SolderingIronMen

+0

我有一個解決方法,我將在下面添加以供參考。 –

回答

1

似乎延遲是OS需要時間重新採樣數據造成的,並且很難爲所有設備提供一個採樣率。也提到了other posts。所以,我將音頻記錄邏輯移至活動onCreate。當我不需要音頻或暫停時,我只是丟棄數據。

我總是在錄音時沒有觀察到電池耗盡。雖然這可能不是解決此問題的最佳方法,但對我來說,這絕對是一個可接受的解決方法。

+1

此解決方案不適合我,因爲我的最初目標是同步AudioRecord和AudioTrack的啓動。但是現在我明白用Java來做這件事是不可能的。 – SolderingIronMen