我搜索了很多,而且我无法找到解决这个问题的方法。我正在创建一个实时处理音频的应用程序。所以,我创建了一个ASyncTask来初始化麦克风并处理收到的声音:
public class SoundSampler extends AsyncTask<Void, Void, Void>{
AudioRecord recorder;
int bufferSize;
final short[] audioData;
public SoundSampler() {
int samplerate = 44100;
int encoding = AudioFormat.ENCODING_PCM_16BIT;
int config = AudioFormat.CHANNEL_IN_MONO;
bufferSize = AudioRecord.getMinBufferSize(samplerate, config, encoding);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, samplerate, config, encoding, bufferSize);
final int finalBufferSize = bufferSize;
audioData = new short[finalBufferSize];
OnRecordPositionUpdateListener positionUpdater = new OnRecordPositionUpdateListener() {
@Override
public void onPeriodicNotification(AudioRecord recorder) {
// do something amazing with audio data (long operations)
}
@Override
public void onMarkerReached(AudioRecord recorder) { Log.d("Process", "marker reached");
}
};
recorder.setRecordPositionUpdateListener(positionUpdater);
recorder.setPositionNotificationPeriod(64);
Log.d("Process", "starTAGt recording, bufferSize: " + bufferSize);
Log.d("Process", "state = " + recorder.getState() + " aud = " + audioData.length);
}
@Override
protected Void doInBackground(Void... params) {
recorder.startRecording();
Log.d("Process", "rec = " + recorder.getRecordingState());
while (!isCancelled()) {
recorder.read(audioData, 0, bufferSize);
}
recorder.stop();
return null;
}
}
这是我的主要活动onCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button on = (Button) findViewById(R.id.on);
Button off = (Button) findViewById(R.id.off);
final SoundSampler smp = new SoundSampler();
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
smp.execute();
}
});
off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
smp.cancel(true);
}
});
}
现在,声音已注册,但在我启动SoundSampler AsyncTask后,Ui被阻止。我希望SoundSampler能够注册数据,但我希望他能够从主UI中停止。关于这样做你有什么建议吗?
答案 0 :(得分:0)
在UI线程上调用OnRecordPositionUpdateListener
方法。您可以通过在侦听器的方法中插入以下日志语句来确认这一点:
Log.i(TAG, "OnRecordPositionUpdateListener on thread: " + Thread.currentThread().getName());
您必须在onPeriodicNotification(AudioRecord recorder){}