android recording a video, initializing the camera - android

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

Related

MediaRecorder: start called in an invalid state: 4 in video recording

I am making a custom video recorder to record the video.Here is my code
boolean usecamera = true;
boolean previewRunning = false;
SurfaceView surfaceView;
Button btnStart, btnStop;
File root;
File file;
Boolean isSDPresent;
SimpleDateFormat simpleDateFormat;
String timeStamp;
#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.activity_surface);
initComs();
actionListener();
}
private void initComs() {
simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss");
timeStamp = simpleDateFormat.format(new Date());
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
surfaceView = (SurfaceView) findViewById(R.id.preview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
btnStop = (Button) findViewById(R.id.btn_stop);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
isSDPresent = android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long) stat.getBlockSize()
* (long) stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}
private void actionListener() {
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
recorder.stop();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
// Let's prepareRecorder so we can record again
prepareRecorder();
}
}
});
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(surfaceHolder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
} else {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
}
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("onsurfacecreated");
if (usecamera) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("onsurface changed");
if (!recording && usecamera) {
if (previewRunning) {
camera.stopPreview();
}
try {
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth,
camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
prepareRecorder();
if (!recording) {
recording = true;
recorder.start();
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
// camera.lock();
camera.release();
}
finish();
}
}
But when i am running this code it showing the error MediaRecorder: start called in an invalid state: 4.I didn't know what s the problem.I try everything from my side but nothing works.I am new in android please help me.
Please try that:
MediaRecorder mMediaRecorder = new MediaRecorder();
mMediaRecorder.reset();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mMediaRecorder.setOutputFile(directory_path + path);
mMediaRecorder.setVideoSize(width, height);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setVideoEncodingBitRate(bitrate);
mMediaRecorder.setVideoFrameRate(framerate);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();

Media Recorder Crash with logcat message "HwMemBitMask::~HwMemBitMask ************** FORCE FREEING!!!!! "

I am using media recorder to record video with following code. Can any one explain why HwMemBitMask::~HwMemBitMask ************** FORCE FREEING!!!!! message is for ? It happens when method startRecording() code get executed.
public class VideoRecorder extends FragmentActivity implements SurfaceHolder.Callback
{
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
SurfaceView cameraView;
private Camera mCamera;
String filePath;
#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();
filePath = getIntent().getStringExtra("filepath");
initRecorder();
setContentView(R.layout.videorecorder);
cameraView = (SurfaceView) findViewById(R.id.video_surface_view);
holder = cameraView.getHolder();
holder.addCallback(this);
cameraView.setClickable(true);
}
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(filePath);
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 surfaceCreated(SurfaceHolder holder)
{
if(mCamera != null)
{
mCamera.release();
mCamera = null;
}
mCamera = Camera.open();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
mCamera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
if (recording)
{
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
public void recordButtonClick(View view)
{
Button recordButton = (Button)(view);
if(recordButton.getText().toString().contains("Record"))
{
// Recording started
findViewById(R.id.play_stop).setEnabled(false);
((Button)findViewById(R.id.cancel_done)).setText("Done");
findViewById(R.id.cancel_done).setEnabled(false);
startRecording();
findViewById(R.id.blink_recording_text).setVisibility(View.VISIBLE);
recordButton.setText("Stop");
}
else
{
findViewById(R.id.blink_recording_text).setVisibility(View.GONE);
stopRecording();
findViewById(R.id.play_stop).setEnabled(true);
findViewById(R.id.cancel_done).setEnabled(true);
recordButton.setText("Record");
}
}
public void playButtonClick(View v)
{
}
public void doneButtonClick(View v)
{
}
private void startRecording()
{
if (recording)
{
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
}
else
{
recording = true;
recorder.start();
}
}
private void stopRecording()
{
if (recording)
{
recorder.stop();
recording = false;
}
}
}

Android Camera surface-view camera recreated when i press back button on archos tablet on jellybean

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.

Custom Video Recording Screen

I am trying to implement an application which when starts starts video recording automatically with my custom video recording screen with my own button to stop the recording and with other buttons. What I have done is designed the layout with buttons till now but how to add video recording screen in the background..Please help.!
This is how I achieved it:
public class MainActivity extends Activity implements SurfaceHolder.Callback {
private MediaRecorder recorder;
private SurfaceHolder surfaceHolder;
private CamcorderProfile camcorderProfile;
private Camera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
SurfaceView surfaceView;
Button btnStart, btnStop;
File root;
File file;
Boolean isSDPresent;
SimpleDateFormat simpleDateFormat;
String timeStamp;
#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.activity_main);
initComs();
actionListener();
}
private void initComs() {
simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss");
timeStamp = simpleDateFormat.format(new Date());
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
surfaceView = (SurfaceView) findViewById(R.id.preview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
btnStop = (Button) findViewById(R.id.btn_stop);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
isSDPresent = android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long) stat.getBlockSize()
* (long) stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}
private void actionListener() {
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
recorder.stop();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
// Let's prepareRecorder so we can record again
prepareRecorder();
}
}
});
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(surfaceHolder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
} else {
recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + ""
+ new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date())
+ ".mp4");
}
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("onsurfacecreated");
if (usecamera) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("onsurface changed");
if (!recording && usecamera) {
if (previewRunning) {
camera.stopPreview();
}
try {
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth,
camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
prepareRecorder();
if (!recording) {
recording = true;
recorder.start();
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
// camera.lock();
camera.release();
}
finish();
}
}
You can create your own Video Recording Screen
Try like this, First Create a Custom Recorder using SurfaceView
public class VideoCapture extends SurfaceView implements SurfaceHolder.Callback {
private MediaRecorder recorder;
private SurfaceHolder holder;
public Context context;
private Camera camera;
public static String videoPath = Environment.getExternalStorageDirectory()
.getPath() +"/YOUR_VIDEO.mp4";
public VideoCapture(Context context) {
super(context);
this.context = context;
init();
}
public VideoCapture(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public VideoCapture(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
#SuppressLint("NewApi")
public void init() {
try {
recorder = new MediaRecorder();
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
camera = getCameraInstance();
if(android.os.Build.VERSION.SDK_INT > 7)
camera.setDisplayOrientation(90);
camera.unlock();
recorder.setCamera(camera);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setOutputFile(videoPath);
} catch (Exception e) {
e.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
public void surfaceCreated(SurfaceHolder mHolder) {
try {
recorder.setPreviewDisplay(mHolder.getSurface());
recorder.prepare();
recorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopCapturingVideo() {
try {
recorder.stop();
camera.lock();
} catch (Exception e) {
e.printStackTrace();
}
}
#TargetApi(5)
public void surfaceDestroyed(SurfaceHolder arg0) {
if (recorder != null) {
stopCapturingVideo();
recorder.release();
camera.lock();
camera.release();
recorder = null;
}
}
private 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;
}
}
And you can use it inside your Layout for Activity Class
<your_package.VideoCapture
android:id="#+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000" />
EDITED:-
public class CaptureVideo extends Activity {
private VideoCapture videoCapture;
private Button stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_capture);
videoCapture = (VideoCapture) findViewById(R.id.videoView);
stop= (Button) findViewById(R.id.stop);
stop.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
videoCapture.stopCapturingVideo();
setResult(Activity.RESULT_OK);
finish();
}
});
}
}
Hope this will help you
This way is using fragments:
public class CaptureVideo extends Fragment implements OnClickListener, SurfaceHolder.Callback{
private Button btnStartRec;
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
private int randomNum;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view001 = inflater.inflate(R.layout.capture_video,container,false);
recorder = new MediaRecorder();
initRecorder();
btnStartRec = (Button) view001.findViewById(R.id.btnCaptureVideo);
btnStartRec.setOnClickListener(this);
SurfaceView cameraView = (SurfaceView)view001.findViewById(R.id.surfaceCamera);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
return view001;
}
#SuppressLint({ "SdCardPath", "NewApi" })
private void initRecorder() {
Random rn = new Random();
int maximum = 10000000;
int minimum = 00000001;
int range = maximum - minimum + 1;
randomNum = rn.nextInt(range) + minimum + 1 - 10;
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
recorder.setOrientationHint(90);//plays the video correctly
}else{
recorder.setOrientationHint(180);
}
recorder.setOutputFile("/sdcard/MediaAppVideos/"+randomNum+".mp4");
}
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) {
switch (v.getId()) {
case R.id.btnCaptureVideo:
try{
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
//initRecorder();
//prepareRecorder();
} else {
recording = true;
recorder.start();
}
}catch(Exception e){
}
default:
break;
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
// finish();
} catch (Exception e) {
}
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="#+id/surfaceCamera"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/btnCaptureVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Start Recording" />
</RelativeLayout>

Media Recorder Start Failed-22 inside a thread

Hi i am trying to make a video recorder android app> For some reason i need to get its audio, i have tried some libraries but nothing really extracted me the audio. So now my approach is that instead of using native libraries can i record video and audio separately? Main thread records video and another thread records audio. I am getting error when i call start() method of media recorder class inside thread and i get Start Failed -22. Following is my code.
public class MainActivity extends Activity {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec ;
ImageView recordingBt;
public MediaRecorder mrec2 = new MediaRecorder();
File video;
private Camera mCamera;
File audiofile = null;
File audiofile2 = null;
boolean recording=false;
TextView tv;
View myview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordingBt= (ImageView) findViewById(R.id.camera);
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
tv=(TextView) findViewById(R.id.textView1);
myview = findViewById(R.id.MyBigView);
}
#Override
protected void onStart(){
super.onStart();
Log.i("Recording Activity", "we are inside Start function of Recording Activity");
Log.i("Recording Activity", "Opening camera");
mCamera = Camera.open();
Log.i("Recording Activity", "Camera Opened");
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recordingBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recording==false){
try {
Log.i("Recording Activity", "Recording Start");
startRecording();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
stopRecording();
}
}
});}
public void startRecording() throws IOException
{
recording=true;
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
Log.i("Setting Path", sampleDir.toString());
try {
audiofile = File.createTempFile("SqB", ".3gp", sampleDir);
} catch (IOException e) {
return;}
Log.i("Recording Activity", "Seting Media Recorder attributes");
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.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setOutputFile(audiofile.getAbsolutePath());
mrec.prepare();
mrec.start();
startProgress(myview);
}
protected void stopRecording() {
recording=false;
mrec.stop();
mrec.release();
mCamera.lock();
mCamera.release();
mrec2.stop();
mrec.release();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
try {
audiofile2 = File.createTempFile("myAudio", ".mp3", sampleDir);
} catch (IOException e) {
return;}
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat .CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mrec2.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec2.setAudioSamplingRate(16000);
mrec2.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mrec2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec2.setOutputFile(audiofile2.getAbsolutePath());
try {
mrec2.prepare();
} catch (IllegalStateException e1) {
Log.i("Illegal", "Exception");
e1.printStackTrace();
} catch (IOException e1) {
Log.i("Iinput output", "Exception");
}
Log.i("Inside Run Method", "Starting Thread soon there will be issue");
mrec2.start();
Log.i("Inside Run Method", "After start method inside thread");
Log.i("Inside Thread", "Alive");
}
};
new Thread(runnable).start();
}

Categories

Resources