我已经搜索了很多,但我无法找到解决这个问题的方法。我正在创建一个实时处理音频的应用程序。因此,我创建了一个 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 中按我的意愿停止。你对这样做有什么建议吗?