Reputation: 1964
I'm trying to detect if MediaRecorder is used by other application, to stop my recorder and continue for later use. I saw Androids Voice recorder app, it does what exactly I'm talking about, but HOW ? Thank you.
Upvotes: 4
Views: 4136
Reputation: 11
public boolean isMicrophoneAvailable() {
boolean available = true;
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_DEFAULT, 44100);
try {
if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) {
available = false;
}
recorder.startRecording();
if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
recorder.stop();
available = false;
}
recorder.stop();
} finally {
recorder.release();
}
return available;
}
Upvotes: 1
Reputation: 179
When another program is trying to access MediaRecorder, you either get an error or it crashes. In other words, you have exclusive access to it.
You can not get the state of MediaRecorder directly, however you can verify wheter you are recording. Here is the code that does what you want:
package com.aplayer;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class APlayerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaRecorder
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile("/sdcard/test.wav");
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.d("ERROR ","IllegalStateException");
Toast msg = Toast.makeText(APlayerActivity.this, "IllegalStateException", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR ","IOException");
e.printStackTrace();
Toast msg = Toast.makeText(APlayerActivity.this, "IOException", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
try {
recorder.start();
Toast msg = Toast.makeText(APlayerActivity.this, "Recording", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
} catch (Exception e) {
Log.e("ERROR", "start() failed");
Toast msg = Toast.makeText(APlayerActivity.this, "Recording failed", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
}
}
Upvotes: 2