我制作了一个代码,允许我从麦克风录制音频。奇怪的是,当我单击我的按钮时,它似乎有某种滞后,按钮在视觉上保持按下半秒钟,然后启动它方法。这是有原因的,我该如何解决?
我现在拥有的:
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRecord:
if (mStartRecording) {
mRecordButton.setText("Stop Recording");
onRecord(true);
mStartRecording = false;
} else {
mRecordButton.setText("Start Recording");
mStartRecording = true;
onRecord(false);
}
break;
}
编辑 感谢您的帮助,我决定使用服务,但有点挣扎。我建立:
public class RecordService extends IntentService {
private MediaRecorder mRecorder = null;
private String mFileName;
private static final String LOG_TAG = "RecordService";
public RecordService() {
super("RecordService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
}
和
case R.id.bRecord:
if (mStartRecording) {
mRecordButton.setText("Stop Recording");
//onRecord(true);
Intent service = new Intent(myContext, RecordService.class);
myContext.startService(service);
mStartRecording = false;
} else {
mRecordButton.setText("Start Recording");
mStartRecording = true;
onRecord(false);
}
break;
对此有疑问,我现在如何停止此服务(= 停止录制)(通过再次单击按钮)并将想法传达回活动?我试图在服务中添加一个停止功能,但是当我调用 service.stop() 来停止它时它似乎不起作用..