Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Video Recording Not Working in ICS

I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 .

But when I checked in ICS code is not working ?

here I posted code and xml file.

videorecord.java

import java.io.File;
import java.io.IOException;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class videorecord extends Activity{
    SharedPreferences.Editor pre;
    String filename;
    CountDownTimer t;
    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    Integer cnt=0;
    LinearLayout myButton;
    TextView myButton1;
    SurfaceHolder surfaceHolder;
    boolean recording;
    private TextView txtcount;
    private ImageView btnplay;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.videorecord);

        init();

        myCamera = getCameraInstance();
        if(myCamera == null){
        }

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

        Display display = getWindowManager().getDefaultDisplay(); 
           int width = display.getWidth();
           int height = display.getHeight();
        myCameraSurfaceView.setLayoutParams(new LinearLayout.LayoutParams(width, height-60));

        myCameraPreview.addView(myCameraSurfaceView);

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

    private void init() {

        txtcount = (TextView) findViewById(R.id.txtcounter);

        //myButton1 = (TextView) findViewById(R.id.mybutton1);

        btnplay = (ImageView)findViewById(R.id.btnplay);

        t = new CountDownTimer( Long.MAX_VALUE , 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

                cnt++;
                String time = new Integer(cnt).toString();

                long millis = cnt;
                   int seconds = (int) (millis / 60);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                   txtcount.setText(String.format("%d:%02d:%02d", minutes, seconds,millis));

            }

            @Override
            public void onFinish() {            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

         if ((keyCode == KeyEvent.KEYCODE_BACK)) 
         {

             if(recording)
             {
                 new AlertDialog.Builder(videorecord.this).setTitle("Do you want to save Video ?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {


                        public void onClick(DialogInterface dialog, int which) {

                            filename();
                            //finish();
                        }
                    }).setNegativeButton("Cancle", new DialogInterface.OnClickListener() {


                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub

                        }
                    }).show();
             }
             else
             {
                 if ((keyCode == KeyEvent.KEYCODE_BACK))
                 {
                            //Intent homeIntent= new Intent(Intent.ACTION_MAIN);
                        //homeIntent.addCategory(Intent.CATEGORY_HOME);
                        //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //startActivity(homeIntent);

                        //this.finishActivity(1);
                     finish();

                }

                 //moveTaskToBack(true);


            //   finish();
                        return super.onKeyDown(keyCode, event);
                    }
             }
         else
         {
            // Toast.makeText(getApplicationContext(), "asd", Toast.LENGTH_LONG).show();
             android.os.Process.killProcess(android.os.Process.myPid()) ;
         }



        return super.onKeyDown(keyCode, event);
    }

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

        public void onClick(View v) {




                    if(recording){

                Log.e("Record error", "error in recording .");   
                mediaRecorder.stop();  

                t.cancel();
                filename();
                releaseMediaRecorder(); 


            }else{


                releaseCamera();

                   Log.e("Record Stop error", "error in recording .");
                //
                if(!prepareMediaRecorder()){
                    prepareMediaRecorder();
                    finish();
                }

                mediaRecorder.start();

                recording = true;
            //  myButton1.setText("STOP Recording");
            //  btnplay.setImageResource(android.R.drawable.ic_media_pause);

                btnplay.setImageResource(R.drawable.stoprec);
                t.start();
            }


        }};

    private Camera getCameraInstance(){

        Camera c = null;
        try {
            c = Camera.open(); 
        }
        catch (Exception e){

        }
        return c; 
    }

    private void filename()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Save Video");
        alert.setMessage("Enter File Name");


        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if(input.getText().length()>=1)
            {
                filename = input.getText().toString();
                File sdcard = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");

                File from = new File(sdcard,"null.mp4");
                File to = new File(sdcard,filename+".mp4");
                from.renameTo(to);
                SharedPreferences sp = videorecord.this.getSharedPreferences("data", MODE_WORLD_WRITEABLE);
                pre = sp.edit();
                pre.clear();
                pre.commit();
                pre.putString("lastvideo", filename+".mp4");
                pre.commit();
                //btnplay.setImageResource(android.R.drawable.ic_media_play);
                btnplay.setImageResource(R.drawable.startrec);
            //  Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);

                Intent myIntent = new Intent(getApplicationContext(), StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(myIntent);

            }
            else
            {
                filename();
            }

          }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

             // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);
              File file = new File(Environment.getExternalStorageDirectory() + "/VideoRecord/null.mp4");
              //boolean deleted = file.delete();
              file.delete();
              finish();
          }
        });

        alert.show();
    }
    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_HIGH));


        File folder = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");

        boolean success = false;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (!success) {

        } else {

        }

        mediaRecorder.setOutputFile("/sdcard/VideoRecord/"+filename+".mp4");

        mediaRecorder.setMaxDuration(60000); 
        mediaRecorder.setMaxFileSize(5000000); 

        Display display = getWindowManager().getDefaultDisplay();



        int width = display.getHeight();
        int height = display.getWidth();

        String s = new String();
        s= s.valueOf(width);

        String s1 = new String();
        s1= s1.valueOf(height);

      //  Toast.makeText(videorecord.this, "Width : " + s , Toast.LENGTH_LONG).show();
      //  Toast.makeText(videorecord.this, "Height : " +  s1 , Toast.LENGTH_LONG).show();

        mediaRecorder.setVideoSize(height, width);

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

    private void releaseMediaRecorder()
    {
        if (mediaRecorder != null) {
            mediaRecorder.reset();   
            mediaRecorder.release(); 
            mediaRecorder = null;
            myCamera.lock();           
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();      
            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;


            mHolder = getHolder();
            mHolder.addCallback(this);

            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }


        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {

            if (mHolder.getSurface() == null){

              return;
            }


            try {
                mCamera.stopPreview();
            } catch (Exception e){

            }

            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }


        public void surfaceCreated(SurfaceHolder holder) {
               try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }


        public void surfaceDestroyed(SurfaceHolder holder) {


        }
    }
}

videorecord.xml

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

    <FrameLayout android:layout_width="fill_parent" 
    android:layout_height="fill_parent" >

    <FrameLayout 
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"></FrameLayout>

    <LinearLayout 

       android:id="@+id/mybutton" 
     android:layout_width="fill_parent" 
     android:layout_marginBottom="0dip" 
    android:layout_height="wrap_content" android:orientation="horizontal"
     android:layout_weight="0" >

<!-- 
    <TextView  
       android:text="START Recording"
        android:id="@+id/mybutton1"
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"
        style="@style/savestyle"
         android:layout_weight="1"
        android:gravity="left"

         >
         </TextView>
     -->
    <ImageView   android:layout_height="wrap_content" android:id="@+id/btnplay"
    android:padding="5dip"
     android:background="#A0000000"
        android:textColor="#ffffffff"
        android:layout_width="wrap_content" android:src="@drawable/startrec" />
     </LinearLayout>
     <TextView 
    android:text="00:00:00"

    android:id="@+id/txtcounter"



          android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 

        android:layout_gravity="right|bottom"

        android:padding="5dip"

        android:background="#A0000000"
        android:textColor="#ffffffff"


     />
    </FrameLayout>

    <RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@color/bgcolor" >


<LinearLayout android:layout_above="@+id/mybutton"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


</LinearLayout>
</RelativeLayout>
</LinearLayout>
like image 362
Nirav Ranpara Avatar asked Oct 15 '12 06:10

Nirav Ranpara


1 Answers

this may helps you,i have recently working on it and works but here i m using Intent, here getting video from Camera and write it in sdcard folder and using that path this video play.hop it helps full

private final int VIDEO_RESULT = 1;

Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
    btnOk.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // mpopup.dismiss(); //dismissing the popup
            mpopup.dismiss();
            PackageManager pm = getPackageManager();
            if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

                try{
                    Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
                    //i.putExtra(MediaStore.EXTRA_OUTPUT,MyFileContentProviderVideo.CONTENT_URI);
                    startActivityForResult(i, VIDEO_RESULT);

                }catch(Exception e){

                }                   
            } else {
                Toast.makeText(getBaseContext(), "Camera is not available",Toast.LENGTH_LONG).show();
            }

        }
    });


public void onActivityResult(int requestCode, int resultCode, Intent data) {

    selectedVideos = new ArrayList<String>();       

    if (resultCode == RESULT_OK && requestCode == VIDEO_RESULT) {
        try {           

            uriVideo = data.getData();
            //Toast.makeText(ProfileVideo.this,uriVideo.getPath(), Toast.LENGTH_LONG).show();

            selectedImagePath = uriVideo.getPath();
            //selectedImages = new ArrayList<String>();

            byte[] ba = getCapturedVideoStream(ProfileVideo.this, data);
            MyWrite(ba);


            //selectedImagePath = Base64.encodeBytes(ba);           
            selectedVideos.add(selectedImagePath);

    }       

}




public void MyWrite(byte[] buffer)
    {       
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
        directory.mkdirs();
        //Now create the file in the above directory and write the contents into it
        File file = new File(directory, "sample.mp4");      
        selectedImagePath = file.getAbsolutePath();     
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedOutputStream osw = new BufferedOutputStream(fOut);
        try {
            //osw.write(path);
            osw.write(buffer);
            //osw.write(buffer, offset, length);            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }




public static byte[] getCapturedVideoStream(Context ctx, Intent data)
{       
    try 
    {
        AssetFileDescriptor videoAsset = ctx.getContentResolver().openAssetFileDescriptor(data.getData(), "r");
        FileInputStream fis = videoAsset.createInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try 
        {
            for (int readNum; (readNum = fis.read(buf)) != -1;)                
                bos.write(buf, 0, readNum);
        } 
        catch (IOException e) 
        {
           // CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    } 
    catch (IOException e) 
    {
        //CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
        return null;
    }       
}
like image 117
Ankitkumar Makwana Avatar answered Oct 19 '22 03:10

Ankitkumar Makwana