我搜索过很多次, 我无法找到解决这个问题的办法。 我将创建一个实时处理音频的应用程序。 因此, 我创建了一个 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;
}
}
这是我在Create的主要活动:
@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);
}
});
}
现在,声音已经注册了, 但是在我开始音频Sampler Asynctask 之后, Ui 就会被封住。 我希望音频Sampler 注册数据, 但我希望他停止, 正如我想从主界面中停止那样。 您对这样做有什么建议吗?