I am developing an application in which i need to move from capture mode to recording mode(video) and vice versa.
Please help me for this I am cluless here,
please suggest me if any tutorial available for this.
Any kind of help appreciated.
Thank you.
Create a Boolean variable Boolean video = false; Now depending on the switch state, toggle the value of the variable. Then whenever you want to start recording / take a picture just check the value of the video variable.
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_VIDEO_CAPTURE = 2;
if(video) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Use this method to open the camera in video mode
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, 1);
}
}
please go through this url for further video basics
Use the following class
public class CaptureVideo 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_PORTRAIT);
recorder = new MediaRecorder();// Instantiate our media recording object
initialiseRecorder();
setContentView(R.layout.view);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.surface_view);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener((OnClickListener) this);
}
private void initialiseRecorder() {
File OutputFile = new File(Environment.getExternalStorageDirectory().getPath());
String video= "/DCIM/100MEDIA/Video";
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);// generally used also includes h264 and best for flash
recorder.setOutputFile(OutputFile.getAbsolutePath()+video+".3gp");
recorder.setMaxDuration(600000);
}
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;
initialiseRecorder();
prepareRecorder();
Toast display = Toast.makeText(this, "Stopped Recording", Toast.LENGTH_SHORT);// toast shows a display of little sorts
display.show();
} else {
recorder.start();
recording = true;
}
}
public void surfaceCreated(SurfaceHolder holder) {
initialiseRecorder();
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();
}
}
Related
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);
I am working on an application in which video capturing is required.
Everything is working fine like:
open camera for Video recording.
video is being recorded for 20 seconds.
video preview and everything.
Issue :
the Issue is when i start video recording then camera app stops the video recording after 20 seconds(which is correct), but user get notified only after 20 seconds that "maximum recoding time reached".
and while recording it is showing :
(recoded time)/(total time which can be recorded).
what i want:
i want to show user (remaining Time)/(20 seconds).
Here is my code:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_VIDEO_CAPTURE = 1;
private static final int MAXIMUM_VIDEO_RECORDING_LIMIT = 20;
private static final int VIDEO_RECORDING_QUALITY = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dispatchTakeVideoIntent();
}
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, MAXIMUM_VIDEO_RECORDING_LIMIT);
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, VIDEO_RECORDING_QUALITY);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri file = data.getData();
}
}
}
How it can be implemented, please help.
Here is a simple video recording example using the MediaRecorder:
In this you can define the video recording max time limit and file size as well.
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();
}
}
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" />
In my code i have camera preview and video recording on button click so my code works well for recording and preview.
but when i press back button then surfaceview create and surface view change method get called after that surfaceview destroy method called so i have to press back button again and at this time it directly call surface destroy ( second time surface create and surface change is not called)
Here is my code any body can help me?
public class VideoCapture extends Activity implements SurfaceHolder.Callback {
public static final String LOGTAG = "VIDEOCAPTURE";
private static final int SELECT_PHOTO = 100;
private MediaRecorder recorder;
private SurfaceHolder holder;
private CamcorderProfile camcorderProfile;
private Camera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
Button recorderButton,selectVideo;
long init,now,time;
Handler handler;
Runnable updater;
SimpleDateFormat df;
Camera.Parameters parameters;
String timeString, timeStamp,selectedVideoPath;
#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);
setContentView(R.layout.main);
handler = new Handler();
df = new SimpleDateFormat("mm:ss");
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
recorderButton = (Button)findViewById(R.id.button);
selectVideo = (Button)findViewById(R.id.videoselect);
final TextView timerText = (TextView)findViewById(R.id.time);
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "/Filme");
if (!dir.exists()) {
dir.mkdirs();
}
// Animation for blinking red dot while recording
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(new OnClickListener(){
#Override
public void onClick(View v) {
camera.autoFocus(new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
//camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
}
});
selectVideo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("video/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
recorderButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (recording) {
recorderButton.setBackgroundResource(R.drawable.recordbutton_background_selector);
recorder.stop();
handler.removeCallbacks(updater); // stop handler
// to refresh media scan on storage
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse
("file://" + Environment.getExternalStorageDirectory())));
String filepath =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+File.separator+"Filme"+File.separator+"Filme_"+timeStamp+".mp4";
Intent i = new Intent(getBaseContext(),VideoCutActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("path", filepath);
getBaseContext().startActivity(i);
finish();
/*
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
// prepareRecorder();
} else {
recorderButton.setBackgroundResource(R.drawable.stopbutton_background_selector);
recording = true;
prepareRecorder();
// recorder.start();
Log.v(LOGTAG, "Recording Started");
}
}
});
// Recording timmer
updater = new Runnable() {
#Override
public void run() {
now=System.currentTimeMillis();
time=now-init;
timeString = df.format(new Date(time));
timerText.setText(timeString);
handler.postDelayed(this, 30);
}
};
}
#Override
protected void onResume() {
super.onResume();
Log.e("onresume", "on resume");
// Open the default i.e. the first rear facing camera.
}
#Override
protected void onPause() {
super.onPause();
// Because the Camera object is a shared resource, it's very
// important to release it when the activity is paused.
if (recording) {
recorder.stop();
recording = false;
recorder.release();
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
else
{
if (camera != null) {
previewRunning = false;
camera.release();
camera = null;
}
}}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
selectedVideoPath = getPath(selectedImage);
Intent i = new Intent(getBaseContext(),VideoCutActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("path", selectedVideoPath);
VideoCapture.this.startActivity(i);
finish();
}
}
}
public String getPath(Uri uri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getBaseContext(), uri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(holder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
recorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+File.separator+"Filme"+File.separator+"Filme_"+timeStamp+".mp4");
Log.v(LOGTAG, "camcorderProfile");
try {
recorder.prepare();
recorder.start();
init = System.currentTimeMillis();
handler.post(updater);
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceCreated");
if (usecamera) {
camera = Camera.open();
parameters = camera.getParameters();
try {
Log.i("Capture","surface created");
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(LOGTAG,e.getMessage());
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(LOGTAG, "surfaceChanged");
if (!recording && usecamera) {
if (previewRunning){
Log.e("Capture","preview is running");
camera.stopPreview();
}
try {
Log.e("Capture","inside try of surface changed");
parameters = camera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
parameters.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
parameters.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(LOGTAG,e.getMessage());
e.printStackTrace();
}
// prepareRecorder();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed");
if (camera != null) {
camera.stopPreview();
}
if (recording) {
try{
Log.e("Capture","inside recording of surface destory");
recorder.stop();
recording = false;
recorder.release();
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
catch (RuntimeException e) {
Log.d("surface destroyed", "Problem in surfaceDestroyed");
e.printStackTrace();
}
}
Based on debugging/discussion on chat:
the first time back is being hit, the existing Camera activity gets destroyed and another one is created. Used the following to follow the changes in the back stack:
adb shell dumpsys activity | grep -i run
No new task is required, so this is useless:
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Apparently, using i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) helps!
I'm not sure why exactly this is helping though. (Especially, because IIUC, with *CLEAR_TOP, the existing instance of the activity on the stack would be used (with onNewIntent), but here (based on the output from dumpsys, a new activity gets created :|). But it works on archos.
I am developing a video player, at the moment it records the video, saves it when StopButton clicked or Maximum limit approached. then i can play it by clicking on the play button. What i want is that when it reaches it maximum limit lets say 60 seconds of video recording it can perform some action like automatically launch the activity which plays the video.
Following is my code:
public class VideoComponent extends Activity {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
private Button stopRecording = null;
private Button play = null;
int BytesPerElement = 2;
File video;
private Camera mCamera;
File audiofile = null;
boolean recording=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
startRecording = (Button)findViewById(R.id.buttonstart);
stopRecording = (Button)findViewById(R.id.button1);
play=(Button)findViewById(R.id.play);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
startRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(recording==false)
startRecording();
} catch (IOException e) {
Log.i("test" , "Video Not starting");
}
}
});
stopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recording=false;
stopRecording();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i= new Intent(getApplicationContext(),VideoPlayer.class);
i.putExtra("URI", audiofile.getAbsolutePath());
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
Log.i("Test" , "Menu thing");
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
Log.i("Test" , "Start Recording");
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i("Self", "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void startRecording() throws IOException
{
recording=true;
File sampleDir = Environment.getExternalStorageDirectory();
try {
audiofile = File.createTempFile("Video", ".3gp", sampleDir);
} catch (IOException e) {
return;}
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat .CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setMaxDuration(60000);
mrec.setAudioSamplingRate(16000);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay( surfaceHolder.getSurface());
mrec.setOutputFile(audiofile.getAbsolutePath());
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.lock();
mCamera.release();
Log.i("testing","going to call Destroyer");
//surfaceDestroyed(surfaceHolder);
//mCamera.stopPreview();
//finish();
}
private void releaseMediaRecorder(){
Log.i("testing","re;ease Media record");
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(){
Log.i("testing","re;ease Camera");
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
The video Player class:
public class VideoPlayer extends Activity {
VideoView videoView;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Create a VideoView widget in the layout file
//use setContentView method to set content of the activity to the layout file which contains videoView
this.setContentView(R.layout.video);
Intent i= getIntent();
String uri=i.getStringExtra("URI");
Log.i("test" , uri);
videoView = (VideoView)this.findViewById(R.id.videoView);
//add controls to a MediaPlayer like play, pause.
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
//Set the path of Video or URI
videoView.setVideoURI(Uri.parse(uri));
//Set the focus
videoView.requestFocus();
videoView.start(); } }
Consider using a CountDownTimer() ...
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
http://developer.android.com/reference/android/os/CountDownTimer.html