I've faced a very strange behavior: sometimes my mediarecorder crashes with an error "Stop failed" and sometimes it works fine. Is there my fault or it is a bug of the system?
I cant't get what is wrong.
private void stopRecording(){
ticker.cancel();
ticker.purge();
recorder.stop();
startBtn.setText("Start");
recordInProcess = false;
markList = locWriteTask.getMarkArray();
mCamera.lock();
recorder.release();
}
private void startRecording(){
startBtn.setText("Stop");
recordInProcess = true;
recorder = new MediaRecorder();
mCamera.unlock();
recorder.setCamera(mCamera);
recorder.setPreviewDisplay(mSurfaceHolder.getSurface());
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setMaxDuration((int) 10000000);
recorder.setVideoSize(320, 240);
recorder.setVideoFrameRate(15);
recorder.setOutputFile(FULL_PATH_TO_LOCAL_FILE + counter + MP4);
try{
recorder.prepare();
} catch (Exception e){
finish();
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
ticker = new Timer();
locWriteTask = new WriteTimeLocationTimerTask(ll);
ticker.schedule(locWriteTask, 0, DELAY);
recorder.start();
}
You may catch a RuntimeException at the MediaRecorder.stop() method.
Example:
MediaRecorder mRecorder = new MediaRecorder();
File mFile = new File("The output file's absolutePath");
... //config the mRecorder
mRecorder.setOutputFile(mFile.getAbsolutePath());
... //prepare() ...
mRecorder.start();
try {
mRecorder.stop();
} catch(RuntimeException e) {
mFile.delete(); //you must delete the outputfile when the recorder stop failed.
} finally {
mRecorder.release();
mRecorder = null;
}
If the recorder is not in a recording state, then the stop could fail.
See
http://developer.android.com/reference/android/media/MediaRecorder.html
add following in your SurfaceCreated(SurfaceHolder holder):
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); //get your own profile
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(camcorderProfile.videoFrameWidth,camcorderProfile.videoFrameHeight);
mCamera.setParameters(parameters);
Experienced the same error: Sometimes my MediaRecorder crashed with an error "Stop failed" and sometimes it worked fine. Adding this solved my problem:
#Override
public void onStop() {
super.onStop();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
}
Related
Hi i am new for android and in my app i have to record audio using timer as like my below image, Using my below i can able record audio but how can do this scenario with help of timer please help me some
My code:-
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.record_button:
startRecording()
break;
case R.id.stop_button:
break;
}
}
private void startRecording() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();
} catch (Throwable t) {
t.printStackTrace();
}
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
Just start a timer in startRecording and stop it in stopRecording. See: https://stackoverflow.com/a/3734070/2324204
You can use a Chronometer which already exists in Android.
Note: Chronometer is a widget that extends TextView so replace your current TextView with the Chronometer.
Example with your code would be:
//....
Chronometer simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
//...
private void startRecording() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();
simpleChronometer.start(); // start a chronometer
//simpleChronometer.setFormat("Time Running - %s"); // set the format for a chronometer
} catch (Throwable t) {
t.printStackTrace();
}
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
simpleChronometer.stop();
}
In case you want to do things manually you can use the Stopwatch class.
I am trying to Record a Video, But It's getting crash at Media Record starts and Media Record Prepare .please Help Me... Here Is My Code...
private boolean startRecording() {
camera.unlock();
try {
mediaRecorder = new MediaRecorder();
mediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.i(TAG, "Error");
}
});
second=0;
minute=0;
recordCountTimer = new CountDownTimer(Long.MAX_VALUE,1000) {
#Override
public void onTick(long millisUntilFinished) {
second++;
if(second>=60){
second=0;
minute++;
}
recordCount.setText(String.format("%02d:%02d",minute,second));
}
#Override
public void onFinish() {
finish();
}
}.start();
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
Log.d(TAG, "A");
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
Log.e(TAG, "B");
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
defaultVideoPath= FileManger.getOutputMediaFile(MEDIA_TYPE_VIDEO).getAbsolutePath();
// uriVid = Uri.parse(FileManger.getOutputMediaFile(MEDIA_TYPE_VIDEO).getAbsolutePath());
// defaultVideoPath = getRealPathFromUri(uriVid);
mediaRecorder.setOutputFile(defaultVideoPath);
mediaRecorder.setVideoSize(recordingCameraSurface.getWidth(), recordingCameraSurface.getHeight());
mediaRecorder.setVideoFrameRate(20);
Log.v(TAG, "C");
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setMaxFileSize(50000);
mediaRecorder.prepare();
Log.w(TAG, "D");
mediaRecorder.start();
Log.e(TAG, "E");
} catch (IOException e) {
releaseMediaRecorder();
return false;
}catch (IllegalStateException t){
releaseMediaRecorder();
return false;
}
return true;
}
It's giving like
RECORDER_OK﹕ B
MediaRecorder﹕ setOutputFormat called in an invalid state: 4
and Here I am Going to next Activity:
Intent intent = new Intent(RecordBuyPage.this,CheckAndSaveActivity.class);
intent.putExtra("VIDEOFILEPATH", defaultVideoPath);
startActivity(intent);
and in the next Activity i am getting the path null like:
player.setDataSource(getIntent().getStringExtra("VIDEOFILEPATH"));
I think My Order Of Calling Media Recorder Is Correct But it also getting trouble at:
mediarecoreder.prepare().
Please Give Some Valid Solution, I tried a lot From Stack overflow, but it's not working.... I think Video Is Not Recording, because when I passed it through intent it's taking null...
I hope you followed this link of sample code(Media Recorder)
https://github.com/googlesamples/android-MediaRecorder
and it has some bugs in it to record media in portrait mode so to fix this issue please follow this link
and in this link you will get your media path where it stored and you can easily pass it to another activity. Have a look I hope it helps you.
to get the path of media on stop capturing you can do this on your CaptureClick method
Log.d("Video file path", CameraHelper.getOutputMediaFile(
CameraHelper.MEDIA_TYPE_VIDEO).toString());
and complete button OnClickListener
public void onCaptureClick(View view) {
if (isRecording) {
// BEGIN_INCLUDE(stop_release_media_recorder)
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
setCaptureButtonText("Capture");
isRecording = false;
releaseCamera();
Log.d("Video file path", CameraHelper.getOutputMediaFile(
CameraHelper.MEDIA_TYPE_VIDEO).toString());
// END_INCLUDE(stop_release_media_recorder)
} else {
// BEGIN_INCLUDE(prepare_start_media_recorder)
new MediaPrepareTask().execute(null, null, null);
// END_INCLUDE(prepare_start_media_recorder)
}
}
Please follow these two links provided above, it might solve your issue.
try this
public class VideoCapture extends Activity implements OnClickListener
,SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
}
Include Permissions in Manifest file :
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
How to pause when use MediaRecorder Recording video.when i use this class,I found can‘t pause,I search google,but can't find good article. if you have good demo please send to my email box,wo le ge qu a zheme mafan yun!
File dir=new File("/sdcard"+Constant.videoDir+file.separator);
if(!dir.exists()){
dir.mkdir();
}
file = new File(dir,CameraTool2.getVideoName());
if (mCamera == null) {
mCamera = Util.getCameraInstance(flag);
}
mCamera.setDisplayOrientation(90);
mCamera.unlock();
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(mCamera);
// int rotation = getPreviewOrientation(this, getCamaraBackId());
mediaRecorder.setOrientationHint(90);//播放的时候画面旋转
mediaRecorder.reset();
// 设置音频录入源
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置视频图像的录入源
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// 设置录入媒体的输出格式
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
// 设置音频的编码格式
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
// 设置视频的编码格式
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// 设置视频的采样率,每秒4帧
mediaRecorder.setVideoFrameRate(4);
mediaRecorder.setMaxDuration(15000);
// 设置录制视频文件的输出路径
mediaRecorder.setOutputFile(file.getAbsolutePath());
// 设置捕获视频图像的预览界面
mediaRecorder.setPreviewDisplay(sv_view.getHolder().getSurface());
mediaRecorder.setOnErrorListener(new OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
// 发生错误,停止录制
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
isRecording = false;
btn_VideoStart.setVisibility(View.VISIBLE);
btn_VideoStop.setVisibility(View.GONE);
Toast.makeText(Activity_Video.this, "录制出错", 0).show();
}
});
// 准备、开始
mediaRecorder.prepare();
mediaRecorder.start();
I m trying to make an app where user can record his voice and can play the voice in funny tone. Like talking tom application but not just that..He shd be able to share that recorded sound file.
I m able to record the sound but not able to save the file in funny tone..its getting saved in original tone.
any suggestions?
private void startRecording() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp4";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
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;
}
I am working with audio recording in Android.
I want to record audio maximum of 1 minute and if user ask to stop before one minute it should be stop.
I have record audio code and it works perfectly.
How can I set time duration it?
If solution is thread.sleep then it's ok. I do something like same:
if (start) {
startRecording();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//What should do ? to stop thread this Thread.sleep(60000);
callToStopRecording();
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(path + mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e("Camera Error", "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
but at stop recoding button, what do I need to write?
You can use this solution:
mRecorder.setMaxDuration(max_duration_ms);
The duation is in ms, so you have to use:
mRecorder.setMaxDuration(6000);