How to pause when use MediaRecorder Recording video - android

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();

Related

Xamarin - How to set/change VideoView display preview orientation

I copied a code from here https://developer.xamarin.com/recipes/android/media/video/record_video/, an instruction on making videostream and I am trying to change some part of it.
I already tried to change the output orientation to 90 using SetOrientationHint(90)
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?
I already tried the rotation in xml and code but the preview became a total black.
This is the code
[Activity(Label = "App2", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
MediaRecorder recorder;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
//Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var record = FindViewById<Button>(Resource.Id.Record);
var stop = FindViewById<Button>(Resource.Id.Stop);
var play = FindViewById<Button>(Resource.Id.Play);
var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
//video.Rotation = 90;
record.Click += delegate
{
if (recorder == null)
recorder = startRecording(video);
else
Toast.MakeText(this, "Now recording", 0).Show();
};
stop.Click += delegate
{
if (recorder != null)
{
stopRecording(recorder);
recorder = null;
}
else
Toast.MakeText(this, "No video recording", 0).Show();
};
play.Click += delegate
{
if (path != null)
playVideo(video);
else
Toast.MakeText(this, "No video available", 0).Show();
};
//recorder = startRecording(video);
}
protected override void OnDestroy()
{
base.OnDestroy();
if (recorder != null)
{
recorder.Release();
recorder.Dispose();
recorder = null;
}
}
private void playVideo(VideoView video)
{
var uri = Android.Net.Uri.Parse(path);
video.SetVideoURI(uri);
video.Start();
}
private static void stopRecording(MediaRecorder recorder)
{
if (recorder != null)
{
recorder.Stop();
recorder.Release();
}
}
private MediaRecorder startRecording(VideoView video)
{
MediaRecorder recorder;
video.StopPlayback();
//video.Holder.AddCallback(this);
//video.Holder.SetType(SurfaceType.PushBuffers);
recorder = new MediaRecorder();
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetOrientationHint(90);
recorder.SetPreviewDisplay(video.Holder.Surface);
if (recorder!=null)
{
try
{
recorder.Prepare();
recorder.Start();
}
catch (Exception)
{
Toast.MakeText(this, "Exception!", 0).Show();
}
}
return recorder;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
}
UPDATE
#Elvis Xia's answer helped a lot.
Here is the new code
[Activity(Label = "App2", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
MediaRecorder recorder;
Android.Hardware.Camera mCamera; //Android.Hardware is used because it will have
//problem with Android.Graphics
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
//Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var record = FindViewById<Button>(Resource.Id.Record);
var stop = FindViewById<Button>(Resource.Id.Stop);
var play = FindViewById<Button>(Resource.Id.Play);
var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
record.Click += delegate
{
if (recorder == null)
recorder = startRecording(video);
else
Toast.MakeText(this, "Now recording", 0).Show();
};
stop.Click += delegate
{
if (recorder != null)
{
stopRecording(recorder, mCamera);
recorder = null;
}
else
Toast.MakeText(this, "No video recording", 0).Show();
};
play.Click += delegate
{
if (path != null)
playVideo(video);
else
Toast.MakeText(this, "No video available", 0).Show();
};
//recorder = startRecording(video);
}
protected override void OnDestroy()
{
base.OnDestroy();
if (recorder != null)
{
recorder.Release();
recorder.Dispose();
recorder = null;
}
}
private void playVideo(VideoView video)
{
var uri = Android.Net.Uri.Parse(path);
video.SetVideoURI(uri);
video.Start();
}
private static void stopRecording(MediaRecorder recorder, Android.Hardware.Camera mCamera)
{
if (recorder != null)
{
recorder.Stop();
recorder.Release();
mCamera.StopPreview();
mCamera.Release();
}
}
private MediaRecorder startRecording(VideoView video)
{
MediaRecorder recorder;
video.StopPlayback();
//video.Holder.AddCallback(this);
//video.Holder.SetType(SurfaceType.PushBuffers);
recorder = new MediaRecorder();
mCamera = GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetOrientationHint(90);
recorder.SetPreviewDisplay(video.Holder.Surface);
if (recorder!=null)
{
try
{
recorder.Prepare();
recorder.Start();
}
catch (Exception)
{
Toast.MakeText(this, "Exception!", 0).Show();
}
}
return recorder;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public static Android.Hardware.Camera GetCameraInstance()
{
Android.Hardware.Camera c = null;
try
{
c = Android.Hardware.Camera.Open();
}
catch (Exception e)
{
}
return c;
}
}
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?
You need to associate Camera with MediaRecorder after setting the rotation degree:
get an Camera Instacnce through GetCameraInstace:
public static Camera GetCameraInstance()
{
Camera c = null;
try
{
c = Camera.Open();
}
catch (Exception e)
{
}
return c;
}
In MainActivity.cs record button click event, associate the camera with MediaRecorder and set the orientation before mCamera.Unlock:
Camera mCamera
...
recorder = new MediaRecorder();
mCamera = ClassName.GetCameraInstance(); //ClassName if in different class.
//else just GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);
recorder.SetVideoSource(VideoSource.Camera);

Android Video Recording using Media Recorder is Not working

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 I can have previewing permanently when capture video for android?

I am writing a video capture app for android. I have preview first time I want to capture. But after I press stop, I no longer get preview when I start recording again. How can I have preview option permanently?
protected void startRecording() throws IOException
{
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED))
{
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(this.Videopath).getParentFile();
if (!directory.exists() && !directory.mkdirs())
{
throw new IOException("Path to file could not be created.");
}
mCamera.stopPreview();
mCamera.unlock();
mrec = new MediaRecorder(); // Works well
mrec.setCamera(mCamera);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mrec.setOutputFile(Videopath);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.prepare();
isRecording=true;
mrec.start();
}
//-------------------------------------------------------------
protected void stopRecording()
{
if(mrec !=null)
mrec.stop();
releaseMediaRecorder();
isRecording=false;
}
//-------------------------------------------------------------
private void releaseMediaRecorder()
{
if (mrec != null)
{
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
//-------------------------------------------------------------
private void releaseCamera()
{
if (mCamera != null)
{
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
//-------------------------------------------------------------
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
try {
mCamera .setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera .startPreview();
}
//-------------------------------------------------------------
#Override
public void surfaceCreated(SurfaceHolder holder)
{
if (mCamera != null)
{
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
try {
mCamera .setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera .startPreview();
}
else
{
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
VideoRecorderActivity.this.finish();
}
}
//-------------------------------------------------------------
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
}
After you press stop recording either you can play the recorded video or if you want to restart your preview then in your stoprecording method do this:
protected void stopRecording()
{
if(mrec !=null)
try{
mrec.stop();
}catch(IllegalStateException e)
{
Log.e(TAG,"Got illegal ");
}
releaseRecorder();
releaseCamera();
isRecording=false;
/*Here do the same process which you do while creating the preview i.e initilize the camera and create the preview */
mCamera = Camera.open();
camera.lock();
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
try{
mCamera .setPreviewDisplay(holder);
mCamera .startPreview();
}catch(IOException e)
{
Log.v(TAG,"could not start the preview ");
e.printStackTrace();
}
}
// release the recorder after recording
private void releaseRecorder() {
if( mrec!=null){
Log.v(TAG, "recorder released");
mrec.release();
mrec=null;
}
}
// release the camera after recording
private void releaseCamera() {
if(mcamera!=null){
try{
mcamera.reconnect();
}catch(IOException e){
e.printStackTrace();
}
Log.v(TAG, "camera released");
mcamera.release();
mcamera=null;
}

android recording a video, initializing the camera

public class FulfillVideoTaskActivity extends Activity implements SurfaceHolder.Callback, OnInfoListener, OnErrorListener{
private Button initBtn = null;
private Button startBtn = null;
private Button stopBtn = null;
private Button playBtn = null;
private Button stopPlayBtn = null;
// save Button should be implemented
private TextView recordingMsg = null;
private VideoView videoView = null;
private SurfaceHolder holder = null;
private Camera camera = null;
private static final String TAG ="RecordVideo";
private MediaRecorder recorder = null;
private String outputFileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulfill_video_task);
// get references to UI elements
initBtn = (Button) findViewById(R.id.initBtn);
startBtn = (Button) findViewById(R.id.startBtn);
stopBtn = (Button) findViewById(R.id.stopBtn);
playBtn = (Button) findViewById(R.id.playBtn);
stopPlayBtn = (Button) findViewById(R.id.stopPlayBtn);
recordingMsg = (TextView) findViewById(R.id.recording);
videoView = (VideoView)this.findViewById(R.id.videoView);
}
public void buttonTapped(View view) {
switch(view.getId()) {
case R.id.initBtn:
initRecorder();
break;
case R.id.startBtn:
beginRecording();
break;
case R.id.stopBtn:
stopRecording();
break;
case R.id.playBtn:
playRecording();
break;
case R.id.stopPlayBtn:
stopPlayback();
break;
}
}
private void stopPlayback() {
videoView.stopPlayback();
}
private void playRecording() {
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoPath(outputFileName);
videoView.start();
stopPlayBtn.setEnabled(true);
}
private void stopRecording() {
if(recorder != null) {
recorder.setOnErrorListener(null);
recorder.setOnInfoListener(null);
try {
recorder.stop();
}
catch(IllegalStateException e) {
//this can happen if the recorder has already stopped.
Log.e(TAG, "Got IllegalStateException in stopRecording");
}
releaseRecorder();
recordingMsg.setText("");
releaseCamera();
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
}
}
private void releaseCamera() {
if(camera != null) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
camera.release();
camera = null;
}
}
private void releaseRecorder() {
if(recorder != null) {
recorder.release();
recorder = null;
}
}
private void beginRecording() {
recorder.setOnInfoListener(this);
recorder.setOnErrorListener(this);
recorder.start();
recordingMsg.setText("RECORDING");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
}
// Initialize the recorder
private void initRecorder() {
if(recorder != null) return;
// The place where the video will be saved.
outputFileName = Environment.getExternalStorageDirectory() + "/videooutput.mp4";
File outFile = new File(outputFileName);
//if File already exists, we delete it
if(outFile.exists())
outFile.delete();
try{
camera.stopPreview();
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setVideoSize(280, 200);
recorder.setVideoFrameRate(15);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setMaxDuration(10000); // limit to 10 seconds
recorder.setPreviewDisplay(holder.getSurface());
recorder.setOutputFile(outputFileName); // setting our output file to our FileName
recorder.prepare();
Log.v(TAG, "MediaRecorder initialized");
initBtn.setEnabled(false);
startBtn.setEnabled(true);
}
//error checking
catch(Exception e) {
Log.v(TAG, "MediaRecorder failed to initialize");
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_fulfill_video_task, menu);
return true;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "in sufaceCreated");
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
}catch (IOException e) {
Log.v(TAG, "Could not start the preview");
e.printStackTrace();
}
initBtn.setEnabled(true);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "got a recording error");
stopRecording();
Toast.makeText(this, "Recording error has occurred. Stopping the recording", Toast.LENGTH_SHORT).show();
}
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.i(TAG, "got a recording event");
if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
Log.i(TAG, "...max duration reached");
stopRecording();
Toast.makeText(this, "Recording limit has been reached. Stopping the recording", Toast.LENGTH_SHORT).show();
}
}
// disable the buttons until the camera is initialized
protected void onResume() {
Log.v(TAG, "in onResume");
super.onResume();
initBtn.setEnabled(false);
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(false);
if(!initCamera())
finish();
}
// initializes the camera
private boolean initCamera() {
try {
camera = Camera.open();
Camera.Parameters camParams = camera.getParameters();
camera.lock();
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(RuntimeException re) {
Log.v(TAG, "Could not initialize the Camera");
re.printStackTrace();
return false;
}
return true;
}
}
Hi, I'm trying to record a video on android right now, when I run my code (the whole code above), the camera can't be initialized. I guess I have an error in the following part.
private boolean initCamera() {
try {
camera = Camera.open();
Camera.Parameters camParams = camera.getParameters();
camera.lock();
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(RuntimeException re) {
Log.v(TAG, "Could not initialize the Camera");
re.printStackTrace();
return false;
}
return true;
}
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); this line in this code gets multiple markers, saying
The method setType(int) from the type SurfaceHolder is deprecated
The field SURFACE_TYPE_PUSH_BUFFERS is deprecated
Does anyone know the reason why I'm getting this?
Try this code
first
setRecorder() ;
SurfaceView videoShootSurfaceView = (SurfaceView) findViewById(R.id.shootVideosurfaceView_VSD);
SurfaceHolder videoSurfaceHolder = videoShootSurfaceView.getHolder();
videoSurfaceHolder.addCallback(this);
videoSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
set the recorder type
public void setRecorder() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// recorder.setVideoSize(640, 480);
recorder.setVideoSize(320, 240);
// recorder.setVideoSize(480, 320);
// recorder.setVideoSize(176, 144);
recorder.setVideoFrameRate(15);
// recorder.setMaxDuration(3600000);
recorder.setMaxDuration(300000);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
}
override this methhod.
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
recorder.setPreviewDisplay(holder.getSurface());
if (recorder != null) {
try {
recorder.prepare();
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IOException", e.toString());
}
}
}
To start the recording
public void startRecording() {
setRecorder();
recorder.setPreviewDisplay(recoderTempHolder.getSurface());
if (recorder != null) {
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IOException", e.toString());
}
}
}
To stop the recording
public void stopRecording() {
recorder.stop();
// recorder.reset();
recorder.release();
}

android mediarecoder saves empty file

This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size. I dont seem to understand what has gone wrong. Any help will be appreciated.
if(mCamera == null) {
mCamera = Camera.open();
mCamera.unlock();
}
if(mediaRecorder == null)
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(mCamera);
mediaRecorder.setCamera(mCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setOutputFile("/sdcard/1.mp4");
mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setVideoSize(176,144);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mediaRecorder.setPreviewDisplay(surface);
mediaRecorder.setMaxFileSize(maxFileSizeInBytes);
mediaRecorder.prepare();
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
// This is thrown if the previous calls are not called with the
// proper order
e.printStackTrace();
}
mediaRecorder.start();
The reason for such behavior is that you are probably (95% sure) calling recorder.setOutputFile() again after you have finished your recording (after recorder.stop() perhaps). Thus old file is being rewritten by new empty file.
okay so i finally figured it out myself. i used the method described here and it worked properly.
http://developer.android.com/guide/topics/media/camera.html#saving-media
The Below code worked for me :
private boolean isRecording = false;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_record);
// Create an instance of Camera
mCamera = getCameraInstance();
mHolder = surfaceViewRecReadyTestimonial.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private boolean prepareVideoRecorder() {
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(surfaceViewRecReadyTestimonial.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
#Override
public void onClick(View v) {
if (v == btnStart) {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
} else if (v == btnStop) {
if (isRecording) {
// 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
isRecording = false;
}
} }
private void releaseMediaRecorder() {
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/**
* Create a File for saving an image or video
*/
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "FolderName");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("FolderName", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("RecordVideo", "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
try {
Camera.Parameters parameters = mCamera.getParameters();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
parameters.setPreviewSize(height, width);
mCamera.setDisplayOrientation(90);
}
if (display.getRotation() == Surface.ROTATION_90) {
parameters.setPreviewSize(width, height);
}
if (display.getRotation() == Surface.ROTATION_180) {
parameters.setPreviewSize(height, width);
}
if (display.getRotation() == Surface.ROTATION_270) {
parameters.setPreviewSize(width, height);
mCamera.setDisplayOrientation(180);
}
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public static final String rootDir = getStorageDir().concat(yours_dir);
...
mediaRecorder.setOutputFile(rootDir);
Do you have set user permission
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Categories

Resources