gpt4 book ai didi

java - AudioRecord 线程中的处理

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:03 25 4
gpt4 key购买 nike

我正在线程中处理 AudioRecord 录制的音频,但是如果我在录音机线程中运行处理,一些帧会丢失。根据android, AudioRecord.read() --> bufferoverflow, how to handle the buffer? ,我需要在单独的线程中运行处理,但是如何呢?我是否需要为每一帧(每秒 2-3 个)创建一个新线程?

这是我当前的解决方案,但我想知道是否有更好的方法来做到这一点?

//in the AudioRecord thread
while (!break_condition) {
int num_read = recorder.read(buffer, 0, buffer.length);
HeavyProcessingRunnable myRunnable = new HeavyProcessingRunnable(buffer);
Thread t = new Thread(myRunnable)
t.start();
}

用于繁重处理的可运行程序

public class HeavyProcessingRunnable implements Runnable {
private byte[] var;
public HeavyProcessingRunnable(byte[] var) {
this.var = var;
}
public void run() {
//if this is executed in audio recorder thread, frames get dropped
someHeavyProcessing(var);
}
}

最佳答案

每次创建一个新线程有点昂贵(discussion) 。最好只创建一次繁重的处理线程并为其提供音频样本。这是一个例子:

// Do it only once.

HandlerThread myHandlerThread = new HandlerThread("my-handler-thread");
myHandlerThread.start();

Handler myHandler = new Handler(myHandlerThread.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
someHeavyProcessing((byte[]) msg.obj, msg.arg1);
return true;
}
});

// In audio recorder thread.
// Mind the handler reference.

while (!break_condition) {
int num_read = recorder.read(buffer, 0, buffer.length);
Message message = myHandler.obtainMessage();
message.obj = buffer;
message.arg1 = num_read;
message.sendToTarget();
}

顺便说一下,提供 num_read 以及音频样本非常重要。

关于java - AudioRecord 线程中的处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40459490/

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