我用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,看資料圖) 。
AudioReceiver的初始化和推出startReceive之間需要很長的時間。什麼可能是問題的原因?
您是否發現此問題的任何解決方案@solderingironmen?我遇到了同樣的問題。 –
@KhatamNaayak,no。如果你遇到同樣的問題,請提出我的問題。 – SolderingIronMen
我有一個解決方法,我將在下面添加以供參考。 –