Thursday 6 March 2014

how to capture video in andriod with dynamic video QUALITY and get base64


Java CODE.....


package com.example.capturevideo_own;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.FROYO)
public class MainActivity extends Activity {

private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
Thread thread;
Button myButton;
SurfaceHolder surfaceHolder;
boolean recording;
private Handler progressBarHandler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

recording = false;

setContentView(R.layout.activity_main);

// Get Camera for preview
myCamera = getCameraInstance();
if (myCamera == null) {
Toast.makeText(MainActivity.this, "Fail to get Camera",
Toast.LENGTH_LONG).show();
}

myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
FrameLayout myCameraPreview = (FrameLayout) findViewById(R.id.videoview);
myCameraPreview.addView(myCameraSurfaceView);

myButton = (Button) findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}

Button.OnClickListener myButtonOnClickListener = new Button.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (recording) {
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object


Intent in = new Intent(MainActivity.this, Start_video.class);
startActivity(in);
finish();
} else {

// Release Camera before MediaRecorder start
releaseCamera();









if (!prepareMediaRecorder()) {
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",
Toast.LENGTH_LONG).show();

}

mediaRecorder.start();
recording = true;
myButton.setText("STOP");




thread = new Thread() {
@Override
public void run() {
try {
while (true) {
sleep(1000);
progressBarHandler.post(new Runnable() {
@SuppressWarnings("deprecation")
public void run() {

if(recording )
{
convert_base64("/sdcard/myvideo.mp4");
}

}
});

}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();


}
}
};

private Camera getCameraInstance() {
// TODO Auto-generated method stub
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
}

@SuppressLint("NewApi")
private boolean prepareMediaRecorder() {
myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();

myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

// mediaRecorder.setProfile(CamcorderProfile
// .get(CamcorderProfile.QUALITY_480P));
mediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_LOW));

mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(6000000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(500000000); // Set max file size 5M

mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
.getSurface());

try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;

}

@Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it
// first
releaseCamera(); // release the camera immediately on pause event
}

private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
myCamera.lock(); // lock camera for later use
}
}

private void releaseCamera() {
if (myCamera != null) {
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}

public class MyCameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {

private SurfaceHolder mHolder;
private Camera mCamera;

public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;

// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int weight, 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
}

// make any resize, rotate or reformatting changes here

// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();

} catch (Exception e) {
}
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw
// the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

}
}
public void convert_base64(String uri)
{



InputStream inputStream = null;
try {
inputStream = new FileInputStream(uri);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
   while ((bytesRead = inputStream.read(buffer)) != -1) {
   output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
long Size_of_image = (long) ((bytes.length));
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

formatFileSize(Size_of_image);



    //  Toast.makeText(getApplicationContext(), encodedString ,Toast.LENGTH_LONG).show();  
    }
public static String formatFileSize(long size) {
String hrSize = null;

double b = size;
double k = size / 1024.0;
double m = ((size / 1024.0) / 1024.0);
double g = (((size / 1024.0) / 1024.0) / 1024.0);
double t = ((((size / 1024.0) / 1024.0) / 1024.0) / 1024.0);

DecimalFormat dec = new DecimalFormat("0.00");

if (t > 1) {
hrSize = dec.format(t).concat(" TB");
} else if (g > 1) {
hrSize = dec.format(g).concat(" GB");
} else if (m > 1) {
hrSize = dec.format(m).concat(" MB");
} else {
hrSize = dec.format(k).concat(" KB");
}
Log.e("sizeeeee", ""+hrSize);
return hrSize;
}
}


..............................
Start_video.java



package com.example.capturevideo_own;

import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class Start_video extends Activity {



VideoView videoView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_video);

videoView = (VideoView) findViewById(R.id.videoView1);

videoView.setVideoPath("/sdcard/myvideo.mp4");
videoView.setMediaController(new MediaController(this));
videoView.start();
}

}

..................................
activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <FrameLayout
            android:id="@+id/videoview"
            android:layout_width="720px"
            android:layout_height="480px" />

        <Button
            android:id="@+id/mybutton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="REC"
            android:textSize="12dp" />
    </LinearLayout>

</LinearLayout>




............................
start_video.xml


<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

 

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

</LinearLayout>




..................................
AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.capturevideo_own"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" >
    </uses-permission>
    <uses-permission android:name="android.permission.CAMERA" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.example.capturevideo_own.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          <activity
            android:name="com.example.capturevideo_own.Start_video"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            </activity>
     
    </application>


</manifest>