Skip to main content

How to record and save a video in Android

Let's record a video :). Check the code snippet.

First need to give necessary permissions. So add these permissions to AndroidManifest.xml
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.RECORD_AUDIO" />
MainActivity.java

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
 Button btn_record;
 public static final int MEDIA_TYPE_IMAGE = 1;
 public static final int MEDIA_TYPE_VIDEO = 2;
 private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
 private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
 private Uri fileUri;
 private static final String TAG = MainActivity.class.getSimpleName();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  btn_record = (Button) findViewById(R.id.buttonrecc);
  btn_record.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch (v.getId()) {
  case R.id.buttonrecc:
   reccordVideo();
   break;
  }
 }

 private void reccordVideo() {
  // TODO Auto-generated method stub
  Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

  fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
  intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
  intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  // start the video capture Intent
  startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
 }

 @Override
 protected void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  // save file url in bundle as it will be null as screen orientation
  // changes
  outState.putParcelable("file_uri", fileUri);
 }
 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  fileUri = savedInstanceState.getParcelable("file_uri");
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // if the result is capturing Image
  if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
   if (resultCode == RESULT_OK) {

    // path of the video can be saved to sdcard,we can get its path
    // on the string pathofvideo
    String pathofvideo = fileUri.getPath();
    System.out.println("filepath...." + pathofvideo);
    System.out.println("hsdgshdg");
   } else if (resultCode == RESULT_CANCELED) {

   // if user cancel recording
   Toast.makeText(getApplicationContext(),"User cancelled video recording", Toast.LENGTH_SHORT).show();

   } else {
   // if any error occurs while recording
   Toast.makeText(getApplicationContext(), "Sorry! Failed to record video", Toast.LENGTH_SHORT).show();
   }
  }
 }

 /**
  * Creating file uri to store image/video
  */
 public Uri getOutputMediaFileUri(int type) {
  return Uri.fromFile(getOutputMediaFile(type));
 }

 private static File getOutputMediaFile(int type) {
  File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Android File Upload");
  // Create the storage directory if it does not exist
  if (!mediaStorageDir.exists()) {
   if (!mediaStorageDir.mkdirs()) {Log.d(TAG, "Oops! Failed create " + "Android File Upload"+ " directory");
    return null;
   }
  }
  // Create a file name
  String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
  File mediaFile;
  if (type == MEDIA_TYPE_VIDEO) {
   mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
  } else {
   return null;
  }

  return mediaFile;
 }
}
activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:id="@+id/buttonrecc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="166dp"
        android:text="RECCORD" />
</RelativeLayout>

Comments

Popular posts from this blog

Server communication in Android

In Android we can communicate with server using HTTP request methods for getting some details from the server.We use RESTful service.Mainly we use two types of HTTP request HTTP GET(),HTTP POST() methods. In some case we have to give some values to the server for fetching some informations, then we use commonly HTTP POST() and if we simply want to request for some datas we use HTTP GET(). Lets see HTTP POST() method. public void getResponse(String a, String b) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("URL"); //here write the url List < NameValuePair > nameValueList = new ArrayList < NameValuePair > (2); nameValueList.add(new BasicNameValuePair("keyword", a)); nameValueList.add(new BasicNameValuePair("keyword", b)); try { httppost.setEntity(new UrlEncodedFormEntity(nameValueList)); HttpResponse response = httpclient.execute(httppost); Log.i(...

How to create a flash light on Android

I always wonder the use of a flash light on a phone. This simple app is more useful than anything. So here is the code to build a flashlight app, MainActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; public class MainActivity extends Activity { ImageButton btnSwitch; private Camera camera; private boolean isFlashOn; private boolean hasFlash; Parameters params; MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // flash switch button ...