gpt4 book ai didi

android - AudioRecord 启动后返回一些空数据

转载 作者:行者123 更新时间:2023-11-29 19:09:45 26 4
gpt4 key购买 nike

我编写了一个标准代码,用于使用 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 缓冲区的开头,有空数据(Nexus 4 上大约有 1000 个样本,见数据图)。

Data graph

从初始化 AudioReceiver 到启动 startReceive 需要很长时间。问题的原因可能是什么?

最佳答案

似乎延迟是由于操作系统需要时间对数据重新采样而导致的,而且很难对所有设备采用一个采样率。 other posts 也提到了.因此,我改为将音频记录逻辑移至 Activity onCreate。当我不需要音频或音频暂停时,我就丢弃数据。

当我一直在录音时,我没有观察到电池电量耗尽。虽然这可能不是解决此问题的最佳方法,但这对我来说绝对是一个可以接受的解决方法。

关于android - AudioRecord 启动后返回一些空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com